package com.dmgis.qxfw.dataservice.businessservice.yysl.controller;


import com.dmgis.entity.DmMapRectangle;
import com.dmgis.entity.DmMapPoint;
import com.dmgis.qxfw.dataservice.businessservice.api.domain.DbConfig;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.qx.*;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.qx.soil_humidity;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.xt.sys_config;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.yj.*;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.zy.*;
import com.dmgis.qxfw.dataservice.businessservice.common.domain.*;
import com.dmgis.qxfw.dataservice.businessservice.common.domain.Warning;
import com.dmgis.qxfw.dataservice.businessservice.common.entity.*;
import com.dmgis.qxfw.dataservice.businessservice.common.entity.MsgMediumSmallScale;
import com.dmgis.qxfw.dataservice.businessservice.common.service.IConfigService;
import com.dmgis.qxfw.dataservice.businessservice.common.util.*;
import com.dmgis.qxfw.dataservice.businessservice.dmgis_mongodb_srv.dataservice.service.Impl.FileRequestService;
import com.dmgis.qxfw.dataservice.businessservice.dmgis_mongodb_srv.dataservice.service.Impl.MongoService1;
import com.dmgis.qxfw.dataservice.businessservice.qxinfo.service.IQxInfoService;
import com.dmgis.qxfw.dataservice.businessservice.yygt.service.IGuoTuService;
import com.dmgis.qxfw.dataservice.businessservice.yyly.service.IForestryfcstService;
import com.dmgis.qxfw.dataservice.businessservice.yysl.pojo.AreaPoji;
import com.dmgis.qxfw.dataservice.businessservice.yysl.pojo.QPF;
import com.dmgis.qxfw.dataservice.businessservice.yysl.service.IWaternfoService;
import com.dmgis.qxfw.dataservice.gisservice.service.ITransformService;
import com.dmgis.qxfw.dataservice.businessservice.yynl.service.IWarnQueryService;
import com.dmgis.weblib.MapCommon;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/*气象信息预报*/
@Controller
@RequestMapping("/xtsl")
public class WaterInfoController {
    private  final String operatingSystem;

    @Autowired
    public WaterInfoController(String operatingSystem) {
        this.operatingSystem = operatingSystem;
    }
    @Resource
    private IWaternfoService forecastInfoService;
    @Resource
    private IConfigService configService;
    @Resource
    private IQxInfoService qxInfoService;
    @Resource
    private IGuoTuService guoTuService;
    @Resource
    IWarnQueryService warnQueryService;
    @Resource
    private IForestryfcstService forestryfcstService;

    @Resource
    private  ITransformService transformService;

    /*引用mongo服务*/
    //MongoService1 ms = new MongoService1();
    FileRequestService ms = new FileRequestService();

    /* 日志记录 */
    private static final Log logger = LogFactory.getLog(WaterInfoController.class);

    /* 初始化火险预警界面 */
    @RequestMapping("/initDZWarningPage")
    @ResponseBody
    public Object initDZWarningPage() {
        ArrayList<Object> arrayList = new ArrayList<>();/* object各种类型数据 */
        DZWarning newestDate = forecastInfoService.getDZWarningNewDate();
        //        // 加载列表
        DateTime datechar = new DateTime(newestDate.getDateChar());// DateTime类型
        String startDate = datechar.AddDays(-1).toDateString();// 开始时间
        String endDate = datechar.toDateString();// 结束时间
        arrayList.add(startDate);// 开始时间
        arrayList.add(endDate);// 结束时间
        return arrayList;
    }

    @RequestMapping("/initPage")
    @ResponseBody
    public Object initPage(HttpServletRequest request) {
        ArrayList<Object> arrayList = new ArrayList<Object>();/* object各种类型数据 */
        String page = request.getParameter("page");
        String table = "";
        if ("MountainFlood".equals(page)) {
            table = "danger_warning";
        }

        DZWarning newestDate = forecastInfoService.getPageNewDate(table);
        // 加载列表
        DateTime datechar = new DateTime(newestDate.getDateChar());// DateTime类型
        String startDate = datechar.AddDays(-1).toDateString();// 开始时间
        String endDate = datechar.toDateString();// 结束时间
        endDate += " 23:59:59";
        arrayList.add(startDate);// 开始时间
        arrayList.add(endDate);// 结束时间
        return arrayList;
    }

    /* 得到水库面坐标信息 */
    @RequestMapping("/shuiKu")
    @ResponseBody
    public Object getShuiKuLike(HttpServletRequest request, Model model) {

        List<water_station> warning = forecastInfoService.initReservoirInfo();
        List<water_station> resultList = new ArrayList<water_station>();
        int count = warning.toArray().length;
        String lgtd = "";
        String lttd = "";
        String stcd = "";
        String stnm = "";
        for (int i = 0; i < count; i++) {
            lgtd = warning.get(i).getLgtd();
            lttd = warning.get(i).getLttd();
            stcd = warning.get(i).getStcd();
            stnm = warning.get(i).getStnm();
            ArrayList<Entites> entites = new ArrayList<Entites>();
            if (warning.get(i).getDtrange() != null) {
                String[] posArr1 = warning.get(i).getDtrange().split("\\*");

                String[] posArr = warning.get(i).getDtrange().split("\\*");// 三个部分，*分隔
                for (String pos : posArr) {
                    try {
                        if (pos == null || pos.equals("")) {
                            continue;
                        }
                        Entites entity = new Entites();// 实体类：颜色，坐标
                        ArrayList<MyPoint> tempPos = new ArrayList<MyPoint>();// 临时
                        String[] dotset = pos.split(";");// 坐标数组
                        int ii = 0;
                        for (String strDot : dotset) {
                            String[] dot = strDot.split(",");
                            DmMapPoint dmDot = new DmMapPoint(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));

                            MyPoint dm = new MyPoint(dmDot.x, dmDot.y);
                            tempPos.add(dm);
                            ii++;
                        }
                        entity.setPosArr(tempPos);
                        entity.setColor("#B2FECE");
                        entites.add(entity);
                    } catch (Exception e) {
                        System.err.println(e.getStackTrace());
                    }
                }
                water_station water_station = new water_station();
                water_station.setEntites(entites);
                water_station.setStcd(stcd);
                water_station.setStnm(stnm);
                water_station.setLgtd(lgtd);
                water_station.setLttd(lttd);
                System.out.println(entites);
                resultList.add(water_station);
            }
        }
        return resultList;
    }


    /* 获取水库入库流量预报结果信息*/
    @RequestMapping("/GetInboundFlowFcstInfo")
    @ResponseBody
    public Object getInboundFlowFcstInfo(HttpServletRequest request, Model model) throws Exception {
        reservoir_water_fcst selectKey = new reservoir_water_fcst();// 查询类
        String datechar = request.getParameter("datechar");
        String timechar = request.getParameter("timechar");
        String ntimes = request.getParameter("ntimes");
        selectKey.setDatechar(datechar);
        selectKey.setTimechar(timechar);
        selectKey.setNtimes(ntimes);
        List<reservoir_water_fcst> reservoirList = forecastInfoService.getInboundFlowFcstInfo(selectKey); // 获取水库入库流量预报结果信息
        List<water_station> station = forecastInfoService.initReservoirInfo();
        if (reservoirList.size() > 0) {
            for (int i = 0; i < reservoirList.size(); i++) {
                String stationid = reservoirList.get(i).getStationid();
                for (int j = 0; j < station.size(); j++) {
                    if (station.get(j).getStcd().equals(stationid)) {
                        reservoirList.get(i).setLongitude(Float.parseFloat(station.get(j).getLgtd()));
                        reservoirList.get(i).setLatitude(Float.parseFloat(station.get(j).getLttd()));
                        reservoirList.get(i).setLon(Float.parseFloat(station.get(j).getLgtd()));
                        reservoirList.get(i).setLat(Float.parseFloat(station.get(j).getLttd()));
                        break;
                    }
                }
            }
        } else {
            reservoir_water_fcst fcst = new reservoir_water_fcst();
            fcst = forecastInfoService.GetNewestDate();//得到最新时间
            selectKey.setDatechar(fcst.getDatechar());
            selectKey.setTimechar(fcst.getTimechar());
            reservoirList = forecastInfoService.getInboundFlowFcstInfo(selectKey); // 获取水库入库流量预报结果信息
            if (reservoirList.size() > 0) {
                for (int i = 0; i < reservoirList.size(); i++) {
                    String stationid = reservoirList.get(i).getStationid();
                    for (int j = 0; j < station.size(); j++) {
                        if (station.get(j).getStcd().equals(stationid)) {
                            reservoirList.get(i).setLongitude(Float.parseFloat(station.get(j).getLgtd()));
                            reservoirList.get(i).setLatitude(Float.parseFloat(station.get(j).getLttd()));
                            reservoirList.get(i).setLon(Float.parseFloat(station.get(j).getLgtd()));
                            reservoirList.get(i).setLat(Float.parseFloat(station.get(j).getLttd()));
                            break;
                        }
                    }
                }
            }
        }
        return reservoirList;
    }

    /**
     * 获取七天水库入库流量预报结果信息
     * @param request
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping("/GetInboundFlowFcstInfoDays")
    @ResponseBody
    public Object GetInboundFlowFcstInfoDays(HttpServletRequest request, Model model) throws Exception {
        reservoir_water_fcst selectKey = new reservoir_water_fcst();// 查询类
        String datechar = request.getParameter("datechar");
        String timechar = request.getParameter("timechar");
        String ntimes = request.getParameter("ntimes");
        String stationname = request.getParameter("stationname");
        selectKey.setDatechar(datechar);
        selectKey.setTimechar(timechar);
        selectKey.setNtimes(ntimes);
        selectKey.setStationname(stationname);
        List<reservoir_water_fcst> reservoirList = forecastInfoService.getInboundFlowFcstInfoDays(selectKey); // 获取水库入库流量预报结果信息
        List<water_station> station = forecastInfoService.initReservoirInfo();
        if (reservoirList.size() > 0) {
            for (int i = 0; i < reservoirList.size(); i++) {
                String stationid = reservoirList.get(i).getStationid();
                for (int j = 0; j < station.size(); j++) {
                    if (station.get(j).getStcd().equals(stationid)) {
                        reservoirList.get(i).setLongitude(Float.parseFloat(station.get(j).getLgtd()));
                        reservoirList.get(i).setLatitude(Float.parseFloat(station.get(j).getLttd()));
                        reservoirList.get(i).setLon(Float.parseFloat(station.get(j).getLgtd()));
                        reservoirList.get(i).setLat(Float.parseFloat(station.get(j).getLttd()));
                        break;
                    }
                }
            }
        }
        return reservoirList;
    }

    /* 得到灌溉预报等级信息 11*/
    @RequestMapping("/GetIrrigationFcstInfo")
    @ResponseBody
    public Object getIrrigationFcstInfo(HttpServletRequest request, Model model) throws Exception {
        reservoir_irrigation_index_fcst selectKey = new reservoir_irrigation_index_fcst();// 查询类
        String strDate = request.getParameter("datechar") + " 00:00:00";// 开始时间
        String timechar = request.getParameter("timechar");// 时次
        String ntimes = request.getParameter("ntimes");  //时效
        String time = "";
        selectKey.setDatechar(strDate);
        selectKey.setTimechar(timechar);
        selectKey.setNtimes(Integer.parseInt(ntimes));
        List<reservoir_irrigation_index_fcst> resultList = new ArrayList<reservoir_irrigation_index_fcst>();// 主
        List<reservoir_irrigation_index_fcst> IrrigationFcst = forecastInfoService.getIrrigationFcstInfo(selectKey); //
        int count = IrrigationFcst.toArray().length;
        if (count > 0) {
            for (int i = 0; i < count; i++) {
                ArrayList<Entites> entites = new ArrayList<Entites>();
                time = IrrigationFcst.get(i).getDatechar().toString();

                if (IrrigationFcst.get(i).getPos() != null) {
                    String[] posArr = IrrigationFcst.get(i).getPos().split("\\*");// 三个部分，*分隔
                    for (String pos : posArr) {
                        try {
                            if (pos == null || pos.equals("")) {
                                continue;
                            }
                            Entites entity = new Entites();// 实体类：颜色，坐标
                            ArrayList<MyPoint> tempPos = new ArrayList<MyPoint>();// 临时
                            String strColor = pos.split("#")[0];// #分隔，第一个代表颜色
                            entity.setColor(strColor);// 存入类
                            String[] dotset = pos.split("#")[1].split(",");// 坐标数组
                            int ii = 0;
                            for (String strDot : dotset) {
                                String[] dot = strDot.split(" ");
                                DmMapPoint dmDot = new DmMapPoint(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
//                                DmMapPoint ltDot = transformService.LambertConvertToLonLat(dmDot.x, dmDot.y);
                                MyPoint dm = new MyPoint(dmDot.x, dmDot.y);
                                tempPos.add(dm);
                                ii++;
                            }
                            entity.setPosArr(tempPos);
                            entites.add(entity);
                        } catch (Exception e) {
                            System.err.println(e.getStackTrace());
                        }

                        Collections.sort(entites, new SortByColor());// 排序
                        reservoir_irrigation_index_fcst nwarning = new reservoir_irrigation_index_fcst();// 总
                        nwarning.setDatechar(time);
                        nwarning.setTimechar(timechar);
                        nwarning.setNtimes(Integer.parseInt(ntimes));
                        nwarning.setEntites(entites);
                        nwarning.setPos(IrrigationFcst.get(i).getPos());
                        resultList.add(nwarning);
                    }
                }
            }
        } else {
            reservoir_irrigation_index_fcst fcst = new reservoir_irrigation_index_fcst();
            fcst = forecastInfoService.GetIrrigationNewestDate();//得到最新时间
            selectKey.setDatechar(fcst.getDatechar());
            selectKey.setTimechar(fcst.getTimechar());
            IrrigationFcst = forecastInfoService.getIrrigationFcstInfo(selectKey);
            count = IrrigationFcst.toArray().length;
            for (int i = 0; i < count; i++) {
                ArrayList<Entites> entites = new ArrayList<Entites>();
                time = IrrigationFcst.get(i).getDatechar().toString();

                if (IrrigationFcst.get(i).getPos() != null) {
                    String[] posArr = IrrigationFcst.get(i).getPos().split("\\*");// 三个部分，*分隔
                    for (String pos : posArr) {
                        try {
                            if (pos == null || pos.equals("")) {
                                continue;
                            }
                            Entites entity = new Entites();// 实体类：颜色，坐标
                            ArrayList<MyPoint> tempPos = new ArrayList<MyPoint>();// 临时
                            String strColor = pos.split("#")[0];// #分隔，第一个代表颜色
                            entity.setColor(strColor);// 存入类
                            String[] dotset = pos.split("#")[1].split(",");// 坐标数组
                            int ii = 0;
                            for (String strDot : dotset) {
                                String[] dot = strDot.split(" ");
                                DmMapPoint dmDot = new DmMapPoint(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                                DmMapPoint ltDot = transformService.LambertConvertToLonLat(dmDot.x, dmDot.y);
                                MyPoint dm = new MyPoint(ltDot.x, ltDot.y);
                                tempPos.add(dm);
                                ii++;
                            }
                            entity.setPosArr(tempPos);
                            entites.add(entity);
                        } catch (Exception e) {
                            System.err.println(e.getStackTrace());
                        }
                    }
                    Collections.sort(entites, new SortByColor());// 排序
                    reservoir_irrigation_index_fcst nwarning = new reservoir_irrigation_index_fcst();// 总
                    nwarning.setDatechar(time);
                    nwarning.setTimechar(timechar);
                    nwarning.setNtimes(Integer.parseInt(ntimes));
                    nwarning.setEntites(entites);
                    nwarning.setPos(IrrigationFcst.get(i).getPos());
                    resultList.add(nwarning);
                }
            }
        }
        return resultList;
    }

    /* 得到预警信息 */
    @RequestMapping("/getDZwarning")
    @ResponseBody
    public Object getDZwarning(HttpServletRequest request, Model model) throws Exception {
        DZwarningSearch selectKey = new DZwarningSearch();// 查询类
        String startDate = request.getParameter("startDate") + ":00:00";// 开始时间
        String endDate = request.getParameter("endDate") + ":59:59";// 结束时间
        String type = request.getParameter("type");
        String time = "";
        String docpath = "";
        Integer docid;
        selectKey.setStartDate(startDate);
        selectKey.setEndDate(endDate);
        selectKey.setType(type);
        List<Warning> resultList = new ArrayList<Warning>();// 主
        List<DZWarning> warning = forecastInfoService.getDZWarning(selectKey); //

        int count = warning.toArray().length;
        for (int i = 0; i < count; i++) {
            ArrayList<Entites> entites = new ArrayList<Entites>();
            if (warning.get(i).getGradeArea2() != null && !warning.get(i).getGradeArea2().equals("")) {
                warning.get(i).setWarntype("蓝色预警");
            }
            if (warning.get(i).getGradeArea3() != null && !warning.get(i).getGradeArea3().equals("")) {
                warning.get(i).setWarntype("黄色预警");
            }
            if (warning.get(i).getGradeArea4() != null && !warning.get(i).getGradeArea4().equals("")) {
                warning.get(i).setWarntype("橙色预警");
            }
            if (warning.get(i).getGradeArea5() != null && !warning.get(i).getGradeArea5().equals("")) {
                warning.get(i).setWarntype("红色预警");
            }
            time = warning.get(i).getDateChar().toString();
            Date date = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.UK).parse(time);
            // 格式化
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String sDate = sdf.format(date);// 时间
            docid = warning.get(i).getDocid();
            docpath = warning.get(i).getDocpath();// 文档位置
            if (warning.get(i).getPos() != null) {
                String[] posArr = warning.get(i).getPos().split("\\*");// 三个部分，*分隔
                for (String pos : posArr) {
                    try {
                        if (pos == null || pos.equals("")) {
                            continue;
                        }
                        Entites entity = new Entites();// 实体类：颜色，坐标
                        ArrayList<MyPoint> tempPos = new ArrayList<MyPoint>();// 临时
                        String strColor = pos.split("#")[0];// #分隔，第一个代表颜色
                        entity.setColor(strColor);// 存入类
                        String[] dotset = pos.split("#")[1].split(",");// 坐标数组
                        int ii = 0;
                        for (String strDot : dotset) {
                            String[] dot = strDot.split(" ");
                            DmMapPoint dmDot = new DmMapPoint(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
//                            DmMapPoint ltDot = transformService.LambertConvertToLonLat(dmDot.x, dmDot.y);
                            MyPoint dm = new MyPoint(dmDot.x, dmDot.y);
                            tempPos.add(dm);
                            ii++;
                        }
                        entity.setPosArr(tempPos);
                        entites.add(entity);
                    } catch (Exception e) {
                        System.err.println(e.getStackTrace());
                    }
                }
                Collections.sort(entites, new SortByColor());// 排序
                Warning nwarning = new Warning();// 总
                nwarning.setDocpath(docpath);
                nwarning.setWarntype(warning.get(i).getWarntype());
                nwarning.setDateChar(sDate);
                nwarning.setDocid(docid);
                nwarning.setEntites(entites);
                nwarning.setPos(warning.get(i).getPos());
                resultList.add(nwarning);
            }
        }
        return resultList;
    }


    /* 得到预警信息 */
    @RequestMapping("/getMountainFlood")
    @ResponseBody
    public Object getMountainFlood(HttpServletRequest request, Model model) throws Exception {
        DZwarningSearch selectKey = new DZwarningSearch();// 查询类
        String startDate = request.getParameter("startDate") + ":00:00";// 开始时间
        String endDate = request.getParameter("endDate") + ":59:59";// 结束时间
        String type = request.getParameter("type");

        selectKey.setStartDate(startDate);
        selectKey.setEndDate(endDate);
        selectKey.setType(type);
        List<Warning> resultList = new ArrayList<Warning>();// 主
        List<Danger_warning> warning = forecastInfoService.getMountainFlood(selectKey);

        return warning;
    }

    /* 面实体排序 */
    class SortByColor implements Comparator<Object> {
        public int compare(Object o1, Object o2) {
            // TODO Auto-generated method stub
            Entites entity1 = (Entites) o1;
            Entites entity2 = (Entites) o2;
            if (Integer.parseInt(entity1.getColor()) > Integer.parseInt(entity2.getColor()))
                return -1;
            return 1;
        }
    }

    /*蒸发量查询*/
    @RequestMapping("/Evaporttranspiration")
    @ResponseBody
    public Object rainQuery(HttpServletRequest request, Model model) throws ParseException {
        Date startDate = DateTime.parseDateTime(request.getParameter("startDate")).toDate();
        Date endDate = DateTime.parseDateTime(request.getParameter("endDate")).toDate();
        String[] countys = request.getParameter("countys").split(",");
        String type = request.getParameter("type");
        String element = request.getParameter("element");
        String elemType = request.getParameter("text");
        if (elemType.equals("整点蒸发量")) {
            elemType = "1小时蒸发量";
        }
        if (elemType.equals("累积蒸发量")) {
            elemType = "蒸发量";
        }
        ActualElemQuery elemQuery = new ActualElemQuery();
        elemQuery.setCountys(Arrays.asList(countys));
        elemQuery.setElement(element);
        elemQuery.setStartDate(startDate);
        elemQuery.setEndDate(endDate);
        elemQuery.setType(type);
        List<ActualData> resultList = qxInfoService.qxElementQuery(elemQuery);


        if (resultList.size() == 0) {
            return null;
        }
        List<Object> result = new ArrayList<Object>();
        result.add(classifyElemByValue(resultList, elemType));//resultList, contourSet, elemType
        return result;
    }

    public List<ActualData> classifyElemByValue(List<ActualData> actualDatas, String elemType) {
        for (ActualData actualData : actualDatas) {
            double value = 0d;
            int color = 16777215;// 白色，默认颜色
            switch (elemType) {
                case "蒸发量":
                case "1小时蒸发量":
                    value = actualData.getEvaporation();
                    break;
                default:
                    break;
            }
            actualData.setColor(ColorUtil.transWin32ToHtml(color));
        }
        return actualDatas;
    }

    /* 得到预警文档 */
    @RequestMapping("/getWarningDoc")
    @ResponseBody
    public Object getWarningDoc(HttpServletRequest request, Model model) throws ParseException {
        String docpath = request.getParameter("docpath");// 获取前台文档路径
        if (docpath == null || docpath.equals("")) {
            return "";
        }
        String id = forecastInfoService.getProductID(docpath);// 获取编号
        if (id == null || id.equals("")) {
            return "";
        }
        String urlpath ;
        if (operatingSystem.equals("Windows")){
             urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\slWarning\\";// 临时文件目录
        }else {
             urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/slWarning/";// 临时文件目录
        }


        FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
        FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存

        String fileName = docpath.split("\\\\")[docpath.split("\\\\").length - 1];// 文件名
        String doctype = fileName.split("\\.")[fileName.split("\\.").length - 1];// 文件类型
        String servicePath = "";// 服务器文件
        if (doctype.contains("doc")) {
            String pdfPath = urlpath + fileName.replace(doctype, "pdf");
            File pdfFile = new File(pdfPath);
            if (pdfFile.exists()) {
                if (operatingSystem.equals("Windows")){
                    servicePath = "Temp\\slWarning\\" + fileName.replace(doctype, "pdf");
                }else {
                    servicePath = "Temp/slWarning/" + fileName.replace(doctype, "pdf");
                }

            } else {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("id", id);
                map.put("table_name", "base_product");
                map.put("collectionName", "pdf_file");
                map.put("advCode", DbConfig.advCode);
                byte[] data = ms.selectData(map);
                // 下载doc文件
                if (data == null) {
                    return "";
                }
                FileUtil.bytesToFile(data, pdfPath);
                if (operatingSystem.equals("Windows")){
                    servicePath = "Temp\\slWarning\\" + fileName.replace(doctype, "pdf");
                }else {
                    servicePath = "Temp/slWarning/" + fileName.replace(doctype, "pdf");
                }

            }
        }
        servicePath = servicePath.replace("\\", "/");
        return servicePath;
    }

    /* 得到水文站 */
    @RequestMapping("/getWaterStation")
    @ResponseBody
    public Object getWaterStation() {
        List<WaterStation> resultList = forecastInfoService.getWaterStation();
        return resultList;
    }

    /* 得到水文站经纬度 */
    @RequestMapping("/getWaterStations")
    @ResponseBody
    public Object getWaterStation(HttpServletRequest request, Model model) {
        WaterStation selectKey = new WaterStation();// 查询类
        String stationName = request.getParameter("stationName");
        selectKey.setStnm(stationName);
        List<WaterStation> resultList = forecastInfoService.getWaterStations(selectKey);
        return resultList;
    }


    /* 防汛预案 */
    @RequestMapping("/initFloodPlanPage")
    @ResponseBody
    public Object initFloodPlanPage() throws Exception {
        List<FloodPlan> resultList = new ArrayList<FloodPlan>();// 主
        List<Flooded> flooded = forecastInfoService.getFloodPlan(); //
        int count = flooded.toArray().length;
        for (int i = 0; i < count; i++) {
            ArrayList<Entites> entites = new ArrayList<Entites>();
            Entites entity = new Entites();// 实体类：颜色，坐标
            ArrayList<MyPoint> tempPos = new ArrayList<MyPoint>();// 临时
            String[] dotset = flooded.get(i).getPos().split(",");// 坐标数组
            String levle = flooded.get(i).getWarnLevel();
            FloodPlan floodplan = new FloodPlan();
            int num = dotset.length;
            DmMapPoint[] points = null;
            if (num > 0) {
                Integer index = 0;
                if (num % 2 == 0) {
                    points = new DmMapPoint[num/2];
                }else {
                    points = new DmMapPoint[num/2+1];
                }
                for (int t = 0; t < num; t += 2) {
                    DmMapPoint dmDot = new DmMapPoint(Double.parseDouble(dotset[t]), Double.parseDouble(dotset[t + 1]));
                    MyPoint dm = new MyPoint(dmDot.x, dmDot.y);
                    tempPos.add(dm);
                    points[index] = transformService.LonLatConvertToLambert(dmDot.x, dmDot.y);
                    index++;
                }
            }
            String color = "";
            if (levle.equals("可能性很大")) {
                color = "#FF0000";
            } else if (levle.equals("可能性大")) {
                color = "#FFA500";
            } else {
                color = "#FFFF00";
            }
            MapCommon dmMapCom = new MapCommon();
            int[] parts = new int[1];
            parts[0] = points.length;
            DmMapPoint dmdotCenter = dmMapCom.getPolygonCenterPoint(points, parts, 1);
            DmMapPoint ltDotCenter = transformService.LambertConvertToLonLat(dmdotCenter.x, dmdotCenter.y);
            entity.setPosArr(tempPos);
            entity.setColor(color);
            entites.add(entity);
            String name = flooded.get(i).getName();
            String people = flooded.get(i).getPeople();
            Double waterLev = flooded.get(i).getWaterLev();
            Double waterFlow = flooded.get(i).getWaterFlow();
            String stationName = flooded.get(i).getStationName();
            String warnLevel = flooded.get(i).getWarnLevel();
            floodplan.setName(name);
            floodplan.setPeople(people);
            floodplan.setWaterFlow(waterFlow);
            floodplan.setWaterLev(waterLev);
            floodplan.setStationName(stationName);
            floodplan.setWarnLevel(warnLevel);
            floodplan.setEntites(entites);
            floodplan.setLon(ltDotCenter.x);
            floodplan.setLat(ltDotCenter.y);
            resultList.add(floodplan);
        }
        return resultList;
    }

    /*
      实况水位查询
       */
    @RequestMapping("/findWaterInfo")
    @ResponseBody
    public Object findWaterInfo(HttpServletRequest request, Model model) throws Exception {
        String stationname = request.getParameter("stationname");
        List<reservoir_water_info> resultList = forecastInfoService.findWaterInfo(stationname);
        return resultList;

    }

    /*
      根据预设水位小于滑块值查询flooded所有数据
     */
    @RequestMapping("/findAllFlooded")
    @ResponseBody
    public Object findAllFlooded(HttpServletRequest request, Model model) throws Exception {

        String stationname = request.getParameter("stationname");
        String oldwaterlev = request.getParameter("waterlev");
        Double waterlev = Double.parseDouble(oldwaterlev);
        List<Flooded> resultList = forecastInfoService.findAllFlooded(stationname, waterlev);
        int count = resultList.toArray().length;
        List<FloodPlan> ResultList = new ArrayList<FloodPlan>();// 主
        for (int i = 0; i < count; i++) {
            ArrayList<Entites> entites = new ArrayList<Entites>();
            Entites entity = new Entites();// 实体类：颜色，坐标
            ArrayList<MyPoint> tempPos = new ArrayList<MyPoint>();// 临时
            String[] dotset = resultList.get(i).getPos().split(",");// 坐标数组
            FloodPlan floodplan = new FloodPlan();
            int num = dotset.length;
            DmMapPoint[] points = null;
            if (num > 0) {
                Integer index = 0;
                if (num % 2 == 0) {
                    points = new DmMapPoint[num/2];
                }else {
                    points = new DmMapPoint[num/2+1];
                }
                for (int t = 0; t < num; t += 2) {
                    DmMapPoint dmDot = new DmMapPoint(Double.parseDouble(dotset[t]), Double.parseDouble(dotset[t + 1]));
                    MyPoint dm = new MyPoint(dmDot.x, dmDot.y);
                    tempPos.add(dm);
                    DmMapPoint ltDot = transformService.LonLatConvertToLambert(dmDot.x, dmDot.y);
                    points[index] = ltDot;
                    index++;
                }
            }
            MapCommon dmMapCom = new MapCommon();
            int[] parts = new int[1];
            parts[0] = points.length;
            DmMapPoint dmdotCenter = dmMapCom.getPolygonCenterPoint(points, parts, 1);
            DmMapPoint ltDotCenter = transformService.LambertConvertToLonLat(dmdotCenter.x, dmdotCenter.y);
            entity.setPosArr(tempPos);
            String WarnLevel = resultList.get(i).getWarnLevel();
            if ("可能性很大".equals(WarnLevel)) {
                entity.setColor("#FF0000");
            } else if ("可能性大".equals(WarnLevel)) {
                entity.setColor("#FF8040");
            } else {
                entity.setColor("#FFFF00");
            }
            entites.add(entity);
            String name = resultList.get(i).getName();
            String people = resultList.get(i).getPeople();
            Double waterLev = resultList.get(i).getWaterLev();
            Double waterFlow = resultList.get(i).getWaterFlow();
            String stationName = resultList.get(i).getStationname();
            String warnLevel = resultList.get(i).getWarnLevel();
            floodplan.setName(name);
            floodplan.setPeople(people);
            floodplan.setWaterFlow(waterFlow);
            floodplan.setWaterLev(waterLev);
            floodplan.setStationName(stationName);
            floodplan.setWarnLevel(warnLevel);
            floodplan.setEntites(entites);
            floodplan.setLon(ltDotCenter.x);
            floodplan.setLat(ltDotCenter.y);
            ResultList.add(floodplan);
        }
        return ResultList;
    }


    /* 初始化灾点查询界面 */
    @RequestMapping("/initDPointPage")
    @ResponseBody
    public Object initDPointPage() {
        ArrayList<Object> arrayList = new ArrayList<Object>(); // object各种类型数据
        List<DisasterPoint> countys = forecastInfoService.getDPointCountys();
        List<DisasterPoint> types = forecastInfoService.getDPointTypes();
        // 加载列表

        arrayList.add(countys);// 开始时间
        arrayList.add(types);// 结束时间
        return arrayList;
    }

    /* 得到灾点查询 1*/
    @RequestMapping("/getDPoint")
    @ResponseBody
    public Object getDPoint(HttpServletRequest request, Model model) throws Exception {
        DPoint selectKey = new DPoint();// 查询类
        String countys = request.getParameter("countys");//
        String types = request.getParameter("disTypes");//
        String levels = request.getParameter("levels");
        String disLevels = request.getParameter("disLevels");
        selectKey.setCounty(countys);
        selectKey.setDis_type(types);
        selectKey.setDis_level(levels);
        selectKey.setDanger_level(disLevels);
        List<potential_points> resultList = forecastInfoService.getDPoint(selectKey);
        return resultList;
    }

    /* 得到水利设施查询 */
    @RequestMapping("/getFacilities")
    @ResponseBody
    public Object getFacilities(HttpServletRequest request, Model model) throws Exception {
        List<water_facilities> resultList = forecastInfoService.getFacilities();
        return resultList;
    }

    /* 得到水利灾点查询 */
    @RequestMapping("/getSLPoint")
    @ResponseBody
    public Object getSLPoint(HttpServletRequest request, Model model) throws Exception {
        String county = request.getParameter("county");
        if (StringUtil.IsNullOrEmpty(county))
            county = DbConfig.COUNTY;
        List<potential_points> resultList = forecastInfoService.getSLPoint(county);
        List<DPoint> rstlist = new ArrayList<>();
        for (potential_points p : resultList) {
            DPoint pnt = new DPoint();
            pnt.setPp_id(p.getPp_id().trim());
            pnt.setPp_name(p.getPp_name().trim());
            pnt.setLon(Double.parseDouble(p.getLon()));
            pnt.setLat(Double.parseDouble(p.getLat()));
            pnt.setDis_level(p.getDis_level().trim());
            pnt.setDis_type(p.getDis_type().trim());
            pnt.setDanger_level(p.getDanger_level().trim());
            pnt.setGeo_addr(p.getGeo_addr().trim());
            pnt.setStationName(p.getPp_name().trim());
            pnt.setThreat_pop(p.getThreat_pop());
            pnt.setThreat_prop(p.getThreat_prop());
            rstlist.add(pnt);
        }
        return rstlist;
    }

    /* 初始化历史灾情界面 */
    @RequestMapping("/initDHistoryPage")
    @ResponseBody
    public Object initDHistoryPage() {
        ArrayList<Object> arrayList = new ArrayList<Object>(); // object各种类型数据
        DHistory newestDate = forecastInfoService.getDHistoryNewDate();
        // 加载列表
        // DateTime datechar = new DateTime(newestDate.getDisastertime());//
        // DateTime类型
        String startDate = newestDate.getDisastertime();// 开始时间
        String endDate = newestDate.getDisastertime();// 结束时间
        arrayList.add(startDate);// 开始时间
        arrayList.add(endDate);// 结束时间
        return arrayList;
    }

    /* 得到历史灾情 */
    @RequestMapping("/getDHistory")
    @ResponseBody
    public Object getDHistory(HttpServletRequest request, Model model) throws Exception {
        DHistorySearch selectKey = new DHistorySearch();// 查询类
        String startDate = request.getParameter("startDate");// 开始时间
        String endDate = request.getParameter("endDate");// 结束时间
        String type = request.getParameter("type");
        selectKey.setStartDate(startDate);
        selectKey.setEndDate(endDate);
        selectKey.setTypes(type);

        List<DHistory> resultList = forecastInfoService.getDHistory(selectKey); //

        return resultList;
    }

    /* 初始化乡镇 */
    @RequestMapping("/initCountry")
    @ResponseBody
    public Object initCountry() {
        List<country_point> CountryList = forecastInfoService.getCountry();
        List<Warning> resultList = new ArrayList<Warning>();// 主
        for (int i = 0; i < CountryList.size(); i++) {
            ArrayList<Entites> entites = new ArrayList<Entites>();
            if (CountryList.get(i).getRange() != null) {
                String[] dotset = CountryList.get(i).getRange().split(";");// 三个部分，*分隔
                try {
                    Entites entity = new Entites();// 实体类：颜色，坐标
                    ArrayList<MyPoint> tempPos = new ArrayList<MyPoint>();// 临时
                    int ii = 0;
                    for (String strDot : dotset) {
                        String[] dot = strDot.split(",");
                        DmMapPoint dmDot = new DmMapPoint(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                        MyPoint dm = new MyPoint(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                        tempPos.add(dm);
                        ii++;
                    }
                    entity.setPosArr(tempPos);
                    String strColor = "#87CEFA";// #分隔，第一个代表颜色
                    entity.setColor(strColor);// 存入类
                    entites.add(entity);
                } catch (Exception e) {
                    System.err.println(e.getStackTrace());
                }
                Collections.sort(entites, new SortByColor());// 排序
                Warning nwarning = new Warning();// 总
                nwarning.setEntites(entites);
                resultList.add(nwarning);
            }
        }

        return resultList;
    }

    /* 初始化流域*/
    @RequestMapping("/initWaterShed")
    @ResponseBody
    public Object initWaterShed() {
        List<Rainwatershed> rainwaterList = forecastInfoService.getRainWater();
        List<Warning> resultList = new ArrayList<Warning>();// 主
        for (Rainwatershed rainwater : rainwaterList) {
            ArrayList<Entites> entites = new ArrayList<Entites>();
            String[] strdata = rainwater.getCoordinate().split(";");
            try {
                int ii = 0;
                double xval = 0.0;
                double yval = 0.0;
                Entites entity = new Entites();// 实体类：颜色，坐标
                ArrayList<MyPoint> tempPos = new ArrayList<MyPoint>();// 临时
                for (int i = 0; i < strdata.length; i++) {
                    String[] datatemp = strdata[i].split(",");
                    xval = Double.parseDouble(datatemp[0]);
                    yval = Double.parseDouble(datatemp[1]);
                    DmMapPoint DmDot1 = transformService.LonLatConvertToLambert(xval, yval);
                    MyPoint dm = new MyPoint(xval, yval);
                    tempPos.add(dm);
                    ii++;
                }
                entity.setPosArr(tempPos);
                String strColor = "#87CEFA";// #分隔，第一个代表颜色
                entity.setColor(strColor);// 存入类
                entites.add(entity);
            } catch (Exception e) {
                System.err.println(e.getStackTrace());
            }
            Collections.sort(entites, new SortByColor());// 排序
            Warning nwarning = new Warning();// 总
            nwarning.setEntites(entites);
            resultList.add(nwarning);
        }
        return resultList;
    }

    /* 初始化面雨量 */
    @RequestMapping("/initSmallScale")
    @ResponseBody
    public Object initSmallScale() {
        ArrayList<Object> arrayList = new ArrayList<Object>();/* object各种类型数据 */
        MsgMediumSmallScaleKey newestDate = forecastInfoService.getSmallScaleNewDate();
        // 加载列表
        DateTime observtime = new DateTime(newestDate.getObservTime());// DateTime类型
        String startDate = observtime.AddHours(-1).toDateTimeString();// String类型
        String endDate = observtime.toDateTimeString();// String类型
        arrayList.add(startDate);// 开始时间
        arrayList.add(endDate);// 结束时间

        return arrayList;
    }

    /* 面雨量分析 */
    @RequestMapping("/getSRainfallCountry")           //流域实况面雨量
    @ResponseBody
    public Object getSRainfallCounGetTenDopplertry(HttpServletRequest request, Model model) throws Exception {
        String strDate = request.getParameter("Date");// 时间
        SRainfallSearch selectKey = new SRainfallSearch();// 查询类
        selectKey.setStartDate(strDate);
        selectKey.setNtimes("240");//过去十天
        selectKey.setAreatype("1");//0 流域  1  行政
        selectKey.setType("0");//0 实况  1  预报
        List<area_rain> msgList = forecastInfoService.getSumAreaRain(selectKey);// 雨量
        List<SurfaceRainResult> resultList = new ArrayList<SurfaceRainResult>();// 最终结果
        for (area_rain rainwater : msgList) {
            SurfaceRainResult result = new SurfaceRainResult();
            DecimalFormat df = new DecimalFormat("#.0");
            result.setSurfacerain(Float.parseFloat(df.format(Float.parseFloat(rainwater.getRain()))));
            result.setName(rainwater.getAreaname());
            resultList.add(result);
        }
        return resultList;
    }


    /* 面雨量分析 */
    @RequestMapping("/getSRainfall")           //流域实况面雨量
    @ResponseBody
    public Object getSRainfall(HttpServletRequest request, Model model) throws Exception {
        String strDate = request.getParameter("Date");// 时间
        SRainfallSearch selectKey = new SRainfallSearch();// 查询类
        selectKey.setStartDate(strDate);
        String areatype = request.getParameter("areatype");//0 流域  1  行政
        selectKey.setNtimes(request.getParameter("ntimes"));
        selectKey.setAreatype(areatype);//0 流域  1  行政
        selectKey.setType("0");//0 实况  1  预报
        List<area_rain> fcstList = forecastInfoService.getSumAreaRain(selectKey);// 雨量
        List<SurfaceRainResult> resultList = new ArrayList<SurfaceRainResult>();// 最终结果
        List<Rainwatershed> rainwaterList = forecastInfoService.getRainWater(); // 面雨量流域
        for (Rainwatershed rainwater : rainwaterList) {
            for (area_rain msg : fcstList) {
                if (msg.getAreaname().equals(rainwater.getName())) {
                    SurfaceRainResult result = new SurfaceRainResult();
                    String name = rainwater.getName();
                    Double lon = rainwater.getCenterpointx();
                    Double lat = rainwater.getCenterpointy();
                    result.setName(name);
                    result.setLon(lon);
                    result.setLat(lat);
                    DmMapPoint dmDot = new DmMapPoint(lon, lat);
                    DmMapPoint ltDot = transformService.LonLatConvertToLambert(dmDot.x, dmDot.y);
                    result.setX(ltDot.x);
                    result.setY(ltDot.y);
                    DecimalFormat df = new DecimalFormat("#.0");
                    result.setSurfacerain(Float.parseFloat(df.format(Float.parseFloat(msg.getRain()))));
                    resultList.add(result);
                }
            }
        }
        return resultList;
    }


    /**
     * @Description:水库可增容
     */
    @RequestMapping("/getKeZengRong")
    @ResponseBody
    public Object getKeZengRong(HttpServletRequest request, Model model) throws Exception {
        System.out.println("startDate: "+request.getParameter("startDate"));
        System.out.println("endDate: "+request.getParameter("endDate"));

        SRainfallSearch selectKey = new SRainfallSearch();// 查询类
//        String startDate = request.getParameter("startDate") + ":00:00";// 开始时间
//        String endDate = request.getParameter("endDate") + ":00:00";// 结束时间
        String startDate = request.getParameter("startDate");// 开始时间
        String endDate = request.getParameter("endDate");// 结束时间
        selectKey.setStartDate(startDate);
        List<reservoir> rainwaterList = forecastInfoService.getReservoir(); // 水库
        List<MsgMediumSmallScale> msgList = new ArrayList<MsgMediumSmallScale>();
        selectKey.setEndDate(endDate);
        msgList = forecastInfoService.getSumRain(selectKey);// 雨量
        List<SurfaceRainResult> resultList = new ArrayList<SurfaceRainResult>();// 最终结果
        Double surfacerains = 0.0;
        try {
        for (reservoir rainwater : rainwaterList) {
            if (rainwater.getRange() != null) {
                String[] strdata = rainwater.getRange().split(",");
                double xval = 0.0;
                double yval = 0.0;
                Integer index =0;
                DmMapPoint[] dt =new DmMapPoint[strdata.length / 2];
                for (int i = 0; i < strdata.length / 2; i++) {
                    xval = Double.parseDouble(strdata[2 * i]);
                    yval = Double.parseDouble(strdata[2 * i + 1]);
                    DmMapPoint d_t1 = transformService.LonLatConvertToLambert(xval, yval);
                    dt[index] = d_t1;
                    index++;
                }
                SurfaceRainResult result = new SurfaceRainResult();
                String name = rainwater.getReservoirname();
                Double lon = Double.parseDouble(rainwater.getLon());
                Double lat = Double.parseDouble(rainwater.getLat());
                result.setName(name);
                result.setLon(lon);
                result.setLat(lat);
                DmMapPoint dmDot = new DmMapPoint(lon, lat);
                DmMapPoint ltDot = transformService.LonLatConvertToLambert(dmDot.x, dmDot.y);
                result.setX(ltDot.x);
                result.setY(ltDot.y);

//                Tin dcontour = new Tin();
//                boolean isOn = false;
//                for (MsgMediumSmallScale msg : msgList) {
//                    DmMapPoint dmDotJW = new DmMapPoint(msg.getLon(), msg.getLat());
//                    DmMapPoint dmDotLb = transformService.LonLatConvertToLambert(dmDotJW.x, dmDotJW.y);
//                    dcontour.addpoint(dmDotLb.x, dmDotLb.y, msg.getAmassRain());
//                    isOn = true;
//                }
//
//                if (isOn) {
//                    MapCommon dmMapCom = new MapCommon();
//                    DmMapRectangle rct = dmMapCom.getObjRect(Arrays.asList(dt));
//                    rct.minX = (rct.minX -(rct.maxX-rct.minX));
//                    rct.maxX = (rct.maxX-(rct.maxX-rct.minX));
//                    rct.minY = (rct.minY-(rct.maxY-rct.minY));
//                    rct.maxY = (rct.maxY-(rct.maxY-rct.minY));
//
//                    dcontour.addpoint(rct.minx, rct.miny, 0);
//                    dcontour.addpoint(rct.maxx, rct.maxy, 0);
//                    dcontour.addpoint(rct.minx, rct.maxy, 0);
//                    dcontour.addpoint(rct.maxx, rct.maxy, 0);
//                    dcontour.dmmesh();// 生成
//                    surfacerains = Double.parseDouble(rainwater.getAddcapacityratio())
//                            * dcontour.getarearain1(dpart, (short) 1);
//                } else {
//                    surfacerains = 99999.0;
//                }
                DecimalFormat df = new DecimalFormat("#.0");
                result.setSurfacerain(Float.parseFloat(df.format(surfacerains)));
                resultList.add(result);
            }
        }

        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        return resultList;
    }

    public static DmMapRectangle getObjRect(DmMapPoint[] part) {
        DmMapRectangle rct = new DmMapRectangle();
        rct.maxX=(-Double.MAX_VALUE);
        rct.maxY=(-Double.MAX_VALUE);
        rct.minX=(Double.MAX_VALUE);
        rct.minY=(Double.MAX_VALUE);
            for (int j = 0; j < part.length; j++) {
                DmMapPoint dt = part[j];
                if (dt.x < rct.minX)
                    rct.minX=dt.x;
                if (dt.x > rct.maxX)
                    rct.maxX=dt.x;
                if (dt.y < rct.minY)
                    rct.minY=dt.y;
                if (dt.y > rct.maxY)
                    rct.maxY=dt.y;
            }
        return rct;
    }

    /* 预报面雨量分析 */
    @RequestMapping("/getYBRainfall")
    @ResponseBody
    public Object getYBRainfall(HttpServletRequest request, Model model) throws Exception {
        SRainfallSearch selectKey = new SRainfallSearch();// 查询类
        String time = request.getParameter("date");// 时间
        String sx = request.getParameter("sx");// 时效
        String sc = request.getParameter("sc");// 时效
        String areatype = request.getParameter("areatype");//0 流域  1  行政
        selectKey.setAreatype(areatype);//0 流域  1  行政
        selectKey.setStartDate(time + " " + sc + ":00:00");
        selectKey.setNtimes(sx);
        selectKey.setType("1");//0 实况  1  预报
        List<area_rain> fcstList = forecastInfoService.getSumAreaRain(selectKey);
        List<SurfaceRainResult> resultList = new ArrayList<SurfaceRainResult>();// 最终结果
        if (areatype.equals("0")) {
            List<Rainwatershed> rainwaterList = forecastInfoService.getRainWater(); // 面雨量流域
            for (Rainwatershed rainwater : rainwaterList) {
                for (area_rain msg : fcstList) {
                    if (msg.getAreaname().equals(rainwater.getName())) {
                        SurfaceRainResult result = new SurfaceRainResult();
                        String name = rainwater.getName();
                        Double lon = rainwater.getCenterpointx();
                        Double lat = rainwater.getCenterpointy();
                        result.setName(name);
                        result.setLon(lon);
                        result.setLat(lat);
                        DmMapPoint dmDot = new DmMapPoint(lon, lat);
                        DmMapPoint ltDot = transformService.LonLatConvertToLambert(dmDot.x, dmDot.y);
                        result.setX(ltDot.x);
                        result.setY(ltDot.y);
                        DecimalFormat df = new DecimalFormat("#.0");
                        result.setSurfacerain(Float.parseFloat(df.format(Float.parseFloat(msg.getRain()))));
                        resultList.add(result);
                    }
                }
            }
        } else {
            List<country_point> rainwaterList = forecastInfoService.getCountry(); // 面雨量流域
            for (country_point rainwater : rainwaterList) {
                 for (area_rain rain : fcstList) {
                    if (rain.getAreaname().equals(rainwater.getName())) {
                        //修改为 if (rain.getAreaname().equals(rainwater.getCounty())) {
                        SurfaceRainResult result = new SurfaceRainResult();
                        String name = rainwater.getName();
                        Double lon = rainwater.getLon();
                        Double lat = rainwater.getLat();
                        result.setName(name);
                        result.setLon(lon);
                        result.setLat(lat);
                        DmMapPoint dmDot = new DmMapPoint(lon, lat);
                        DmMapPoint ltDot = transformService.LonLatConvertToLambert(dmDot.x, dmDot.y);
                        result.setX(ltDot.x);
                        result.setY(ltDot.y);
                        DecimalFormat df = new DecimalFormat("#.0");
                        result.setSurfacerain(Float.parseFloat(df.format(Float.parseFloat(rain.getRain()))));
                        resultList.add(result);
                    }
                }
            }
        }
        return resultList;
    }

    /* 预报面雨量分析 */
    @RequestMapping("/getYBRainfallCountry")
    @ResponseBody
    public Object getYBRainfallCountry(HttpServletRequest request, Model model) throws Exception {
        SRainfallSearch selectKey = new SRainfallSearch();// 查询类
        String time = request.getParameter("date");// 时间
        String sx = request.getParameter("sx");// 时效
        String sc = request.getParameter("sc");// 时次
        String areatype = request.getParameter("areatype");//0 流域  1  行政
        selectKey.setAreatype(areatype);//0 流域  1  行政
        selectKey.setStartDate(time + " " + sc + ":00:00");
        selectKey.setNtimes(sx);
        selectKey.setType("1");//0 实况  1  预报
         List<area_rain> fcstList = forecastInfoService.getSumAreaRain(selectKey);
        List<SurfaceRainResult> resultList = new ArrayList<SurfaceRainResult>();// 最终结果
        if (areatype.equals("0")) {
            List<Rainwatershed> rainwaterList = forecastInfoService.getRainWater(); // 面雨量流域
            for (Rainwatershed rainwater : rainwaterList) {
                for (area_rain msg : fcstList) {
                    if (msg.getAreaname().equals(rainwater.getName())) {
                        SurfaceRainResult result = new SurfaceRainResult();
                        String name = rainwater.getName();
                        Double lon = rainwater.getCenterpointx();
                        Double lat = rainwater.getCenterpointy();
                        result.setName(name);
                        result.setLon(lon);
                        result.setLat(lat);
                        DmMapPoint dmDot = new DmMapPoint(lon, lat);
                        DmMapPoint ltDot = transformService.LonLatConvertToLambert(dmDot.x, dmDot.y);
                        result.setX(ltDot.x);
                        result.setY(ltDot.y);
                        DecimalFormat df = new DecimalFormat("#.0");
                        result.setSurfacerain(Float.parseFloat(df.format(Float.parseFloat(msg.getRain()))));
                        resultList.add(result);
                    }
                }
            }
        } else {
            List<country_point> rainwaterList = forecastInfoService.getCountry(); // 面雨量流域
            for (country_point rainwater : rainwaterList) {
                for (area_rain rain : fcstList) {
                    if (rain.getAreaname().equals(rainwater.getName())) {
                        SurfaceRainResult result = new SurfaceRainResult();
                        String name = rainwater.getName();
                        Double lon = rainwater.getLon();
                        Double lat = rainwater.getLat();
                        result.setName(name);
                        result.setLon(lon);
                        result.setLat(lat);
                        DmMapPoint dmDot = new DmMapPoint(lon, lat);
                        DmMapPoint ltDot = transformService.LonLatConvertToLambert(dmDot.x, dmDot.y);
                        result.setX(ltDot.x);
                        result.setY(ltDot.y);
                        DecimalFormat df = new DecimalFormat("#.0");
                        result.setSurfacerain(Float.parseFloat(df.format(Float.parseFloat(rain.getRain()))));
                        resultList.add(result);
                    }
                }
            }
        }
        return resultList;
    }

    /* 预警区内实况信息 */
    @RequestMapping("/getSKinfo")
    @ResponseBody
    public Object
    getSKinfo(HttpServletRequest request, Model model) throws Exception {
        String startDate1 = request.getParameter("startDate");
        String endDate1 = request.getParameter("endDate");
        String startDate = startDate1 + ":00:00";
        String endDate = endDate1 + ":00:00";


        String poss = request.getParameter("pos");// 坐标
        String[] posArr = poss.split("\\*");// 三个部分，*分隔
        List<DmMapPoint> lonlat = new ArrayList<DmMapPoint>();
        List<String> stationids = new ArrayList<String>();
        String skstations = "";
        for (String pos : posArr) {
            try {
                if (pos == null || pos.equals("")) {
                    continue;
                }
                String[] dotset = pos.split("#")[1].split(",");// 坐标数组
                DmMapPoint[] points = new DmMapPoint[dotset.length];
                // DmMapPoint[] point = new DmMapPoint[dotset.length];
                Integer index = 0;
                for (String strDot : dotset) {
                    String[] dot = strDot.split(" ");
                    DmMapPoint dmDot = new DmMapPoint(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                    //point[index] = transformService.LambertConvertToLonLat(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                    points[index] = dmDot;
                    index++;
                }
                MapCommon dmMapCom = new MapCommon();
                DmMapRectangle rect = dmMapCom.getObjRect(Arrays.asList(points));
                DmMapPoint dmDotLb1 = new DmMapPoint(rect.minX, rect.minY);
                DmMapPoint dmDotLb2 = new DmMapPoint(rect.maxX, rect.maxY);
                rect.minX = dmDotLb1.x;
                rect.minY = dmDotLb1.y;
                rect.maxX = dmDotLb2.x;
                rect.maxY = dmDotLb2.y;
                List<smallscale_station> stations = qxInfoService.getStations(rect);
                for (smallscale_station city : stations) {
                    DmMapPoint dmDotJW = new DmMapPoint(city.getLongitude(), city.getLatitude());
                   // DmMapPoint dmDotLb = transformService.LonLatConvertToLambert(dmDotJW.x, dmDotJW.y);
                    if(dmMapCom.pointWithinPolygon(Arrays.asList(points),dmDotJW.x,dmDotJW.y)){
                        if (!skstations.contains(city.getStationid())) {
                            skstations += city.getStationid() + ",";
                            lonlat.add(dmDotJW);
                            stationids.add(city.getStationid());
                        }
                    }
                }
            } catch (Exception e) {
                System.err.println(e.getStackTrace());
            }
        }
        List<MediumSmallScale> resultList = new ArrayList<MediumSmallScale>();
        List<msgmediumsmallscale> dataList = new ArrayList<>();
        if (stationids.size() > 0) {
            dataList = qxInfoService.getSKinfo(startDate, endDate, stationids);
        }
        for (msgmediumsmallscale msg : dataList) {
            MediumSmallScale smallscale = new MediumSmallScale();
            smallscale.setStart(startDate1);
            smallscale.setEnd(endDate1);
            smallscale.setObservTime(msg.getObservtime());
            smallscale.setStationID(msg.getStationid());
            smallscale.setLongitude(msg.getLongitude());
            smallscale.setLatitude(msg.getLatitude());
            smallscale.setLon(msg.getLongitude());
            smallscale.setLat(msg.getLatitude());
            smallscale.setStationName(msg.getStationname());
            smallscale.setRain(Float.parseFloat(String.format("%.1f", msg.getRain())));
            smallscale.setDryBulbTemp(Float.parseFloat(String.format("%.1f", msg.getDrybulbtemp())));
            smallscale.setInstantWindV(Float.parseFloat(String.format("%.1f", msg.getInstantwindv())));
            smallscale.setRelHumidity(msg.getRelhumidity());
            smallscale.setPressureSea(Float.parseFloat(String.format("%.1f", msg.getStationpress())));
            smallscale.setCity(msg.getCity());
            smallscale.setCounty(msg.getCounty());
            DmMapPoint dmDot = new DmMapPoint(msg.getLongitude(), msg.getLatitude());
            DmMapPoint ltDot = transformService.LonLatConvertToLambert(dmDot.x, dmDot.y);
            smallscale.setX(ltDot.x);
            smallscale.setY(ltDot.y);
            resultList.add(smallscale);
        }
        return resultList;
    }

    /* 预警区内预报信息 */
    @RequestMapping("/getYBinfo")
    @ResponseBody
    public Object getYBinfo(HttpServletRequest request, Model model) throws Exception {
        String poss = request.getParameter("pos");// 坐标
        String[] posArr = poss.split("\\*");// 三个部分，*分隔
        List<DmMapPoint> lonlat = new ArrayList<DmMapPoint>();
        List<String> stationids = new ArrayList<String>();
        String ybstations = "";
        for (String pos : posArr) {
            try {
                if (pos == null || pos.equals("")) {
                    continue;
                }
                String[] dotset = pos.split("#")[1].split(",");// 坐标数组
                Integer index = 0;
                DmMapPoint[] points = new DmMapPoint[dotset.length];
                // DmMapPoint[] point = new DmMapPoint[dotset.length];
                for (String strDot : dotset) {
                    String[] dot = strDot.split(" ");
                    DmMapPoint dmDot = new DmMapPoint(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                    // point[index] = transformService.LambertConvertToLonLat(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                    points[index] = dmDot;
                    index++;
                }
                MapCommon dmMapCom = new MapCommon();
                int[] parts = new int[1];
                parts[0] = points.length;
                DmMapPoint dmdotCenter = dmMapCom.getPolygonCenterPoint(points, parts, 1);
                DmMapRectangle rect = dmMapCom.getObjRect(Arrays.asList(points));
                DmMapPoint dmDotLb1 = new DmMapPoint(rect.minX, rect.minY);
                DmMapPoint dmDotLb2 = new DmMapPoint(rect.maxX, rect.maxY);
                rect.minX = dmDotLb1.x;
                rect.minY = dmDotLb1.y;
                rect.maxX = dmDotLb2.x;
                rect.maxY = dmDotLb2.y;
                List<township_station> stations = qxInfoService.getYBStations(rect);
                for (township_station city : stations) {
                    DmMapPoint dmDotJW = new DmMapPoint(city.getLongitude(), city.getLatitude());
                    // DmMapPoint dmDotLb = transformService.LonLatConvertToLambert(dmDotJW.x, dmDotJW.y);
                    if(dmMapCom.pointWithinPolygon(Arrays.asList(points),dmDotJW.x,dmDotJW.y)){
                        if (!ybstations.contains(city.getStationid())) {
                            ybstations += city.getStationid() + ",";
                            lonlat.add(dmDotJW);
                            stationids.add(city.getStationid());
                        }
                    }
                }
            } catch (Exception e) {
                System.err.println(e.getStackTrace());
            }
        }
        List<CityFcstInfo> resultList = new ArrayList<CityFcstInfo>();
        List<township_forecasttemp> fcstList = new ArrayList<township_forecasttemp>();
        if (stationids.size() > 0) {
            fcstList = qxInfoService.getYBinfo(stationids);
        }
        int count = fcstList.toArray().length;
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        if (count > 0) {
            WebCtrlData wcd = new WebCtrlData();
            for (int i = 0; i < count; i += 2) {
                String strStationID = fcstList.get(i).getStationid();
                String strCountyName = fcstList.get(i).getStationname();
                if (strCountyName.contains("乡")) {
                    strCountyName = strCountyName.substring(0, strCountyName.indexOf('乡') + 1);
                }
                if (strCountyName.contains("镇")) {
                    strCountyName = strCountyName.substring(0, strCountyName.indexOf('镇') + 1);
                }
                String weather = "";// 天气信息
                String windD = "";// 风向信息
                String windV = "";// 风速信息
                String windS = "";// 风速信息
                String windD12 = wcd.GetAllFx(fcstList.get(i).getWindd().toString().replace("-65535", "0").trim());
                String windD24 = wcd.GetAllFx(fcstList.get(i + 1).getWindd().toString().replace("-65535", "0").trim());
                String windV12 = wcd.GetWeatherFs(String.valueOf(WebCtrlData.FengSuToFengJi(fcstList.get(i).getWinds())));
                String windV24 = wcd.GetWeatherFs(String.valueOf(WebCtrlData.FengSuToFengJi(fcstList.get(i + 1).getWinds())));
                String windS12 = String.valueOf(fcstList.get(i).getWinds());
                String windS24 = String.valueOf(fcstList.get(i + 1).getWinds());
                if (windD12.equals(windD24)) {
                    windD += windD12;
                } else {
                    windD += windD12 + "转" + windD24;
                }
                if (windV12.equals(windV24)) {
                    windV += windV12;
                } else {
                    windV += windV12 + "~" + windV24;
                }
                if (windS12.equals(windS24)) {
                    windS += windS12 + "m/s";
                } else {
                    windS += windS12 + "~" + windS24 + "m/s";
                }
                if (fcstList.get(i).getWeather1().trim().equals(fcstList.get(i + 1).getWeather1().trim())) {
                    weather += fcstList.get(i).getWeather1().trim();
                } else {
                    weather += fcstList.get(i).getWeather1().trim() + "转" + fcstList.get(i + 1).getWeather1().trim();
                }
                double maxTemp = fcstList.get(i + 1).getMaxtemp();
                double minTemp = fcstList.get(i + 1).getMintemp();
                String pic1 = String.format("%02d",
                        Integer.parseInt(WebCtrlData.WeatherNameToPicPath(fcstList.get(i).getWeather1())));
                String pic2 = String.format("%02d",
                        Integer.parseInt(WebCtrlData.WeatherNameToPicPath(fcstList.get(i + 1).getWeather1())));
                CityFcstInfo fcstInfo = new CityFcstInfo();
                String datechar = format.format(fcstList.get(i).getDatechar());
                Date date = format.parse(datechar);
                DateTime dateTime = new DateTime(date);
                String time1 = dateTime.AddDays(+1).toDateString();
                fcstInfo.setTime1(time1);
                fcstInfo.setTime(datechar);
                fcstInfo.setDatechar(fcstList.get(i).getDatechar());
                fcstInfo.setTimechar(fcstList.get(i).getTimechar());
                fcstInfo.setStationId(strStationID);
                fcstInfo.setStationName(strCountyName);
                fcstInfo.setMinTemp(minTemp);
                fcstInfo.setMaxTemp(maxTemp);
                fcstInfo.setRain(fcstList.get(i).getRain());
                fcstInfo.setWindD(windD);
                fcstInfo.setWindV(windV);
                fcstInfo.setWindS(windS);
                fcstInfo.setPic1(pic1);
                fcstInfo.setPic2(pic2);
                fcstInfo.setLat(fcstList.get(i).getLatitude());
                fcstInfo.setLon(fcstList.get(i).getLongitude());
                // DmMapPoint dt = transformService.LonLatConvertToLambert(fcstInfo.getLon(), fcstInfo.getLat());
                fcstInfo.setX(fcstInfo.getLon());
                fcstInfo.setY(fcstInfo.getLat());
                fcstInfo.setWeather1(fcstList.get(i).getWeather1().trim());
                fcstInfo.setWeather2(fcstList.get(i + 1).getWeather1().trim());
                fcstInfo.setWeather(weather);
                fcstInfo.setHumid(String.valueOf(fcstList.get(i).getHumid()) + "%");
                resultList.add(fcstInfo);
            }
        }
        return resultList;
    }


    /* 地理分析 */
    @RequestMapping("/getAnalysis")
    @ResponseBody
    public Object getAnalysis(HttpServletRequest request, Model model) throws Exception {
        String analysis = request.getParameter("analysis");// 分析图层
        String result = "[";
        if (analysis.contains("灾害点")) {
            String county = request.getParameter("county");
            if (StringUtil.IsNullOrEmpty(county))
                county = DbConfig.COUNTY;
            List<potential_points> resultList = forecastInfoService.getSLPoint(county);
            String poss = request.getParameter("pos");// 坐标
            String[] posArr = poss.split("\\*");// 三个部分，*分隔
            for (String pos : posArr) {
                try {
                    if (pos == null || pos.equals("")) {
                        continue;
                    }
                    String[] dotset = pos.split("#")[1].split(",");// 坐标数组
                    DmMapPoint[] points = new DmMapPoint[dotset.length];
                    Integer index = 0;
                    for (String strDot : dotset) {
                        String[] dot = strDot.split(" ");
                        DmMapPoint dmDot = new DmMapPoint(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                        points[index] = dmDot;
                        index++;
                    }
                    for (potential_points city : resultList) {
                        Double lon = Double.parseDouble(city.getLon().toString());
                        Double lat = Double.parseDouble(city.getLat().toString());
                        DmMapPoint dmDotJW = new DmMapPoint(lon, lat);
                        DmMapPoint dmDotLb = transformService.LonLatConvertToLambert(dmDotJW.x, dmDotJW.y);
                        MapCommon dmMapCom = new MapCommon();
                        if(dmMapCom.pointWithinPolygon(Arrays.asList(points),dmDotLb.x,dmDotLb.y)){
                            result += "{";
                            result += "\"disastername\":\"" + city.getPp_name() + "\",";
                            result += "\"disType\":\"" + city.getDis_type() + "\",";
                            result += "\"dis_type\":\"" + city.getDis_type() + "\",";
                            result += "\"pp_id\":\"" + city.getPp_id() + "\",";
                            result += "\"geo_addr\":\"" + city.getGeo_addr() + "\",";
                            result += "\"threatproperty\":\"" + city.getThreat_pop() + "\",";
                            result += "\"threathouseholds\":\"" + city.getThreat_prop() + "\",";
                            result += "\"lon\":" + lon + ",";
                            result += "\"lat\":" + lat + ",";
                            result += "\"dis_level\":\"" + city.getDis_level() + "\"";
                            result += "},";
                        }
                    }
                } catch (Exception e) {
                    System.err.println(e.getStackTrace());
                }
            }
        } else if (analysis.contains("村点")) {
            String poss = request.getParameter("pos");// 坐标
            String[] posArr = poss.split("\\*");// 三个部分，*分隔
            for (String pos : posArr) {
                try {
                    if (pos == null || pos.equals("")) {
                        continue;
                    }
                    String[] dotset = pos.split("#")[1].split(",");// 坐标数组
                    DmMapPoint[] points = new DmMapPoint[dotset.length];
                    DmMapPoint[] point = new DmMapPoint[dotset.length];
                    Integer index = 0;
                    for (String strDot : dotset) {
                        String[] dot = strDot.split(" ");
                        DmMapPoint dmDot = new DmMapPoint(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                        point[index] = transformService.LambertConvertToLonLat(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                        points[index] = dmDot;
                        index++;
                    }
                    DmMapRectangle rct = new DmMapRectangle();
                    MapCommon dmMapCom = new MapCommon();
                    int[] parts = new int[1];
                    parts[0] = points.length;
                    DmMapPoint dmdotCenter = dmMapCom.getPolygonCenterPoint(points, parts, 1);

                    DmMapRectangle rect = dmMapCom.getObjRect(Arrays.asList(point));
                    DmMapPoint dmDotLb1 = new DmMapPoint(rect.minX, rect.minY);
                    DmMapPoint dmDotLb2 = new DmMapPoint(rect.maxX, rect.maxY);
                    rect.minX = dmDotLb1.x;
                    rect.minY = dmDotLb1.y;
                    rect.maxX = dmDotLb2.x;
                    rect.maxY = dmDotLb2.y;
                    List<village> resultList = qxInfoService.getCountryPoint(rect);
                    for (village city : resultList) {
                        DmMapPoint dmDotJW = new DmMapPoint(city.getLon(), city.getLat());
                        DmMapPoint dmDotLb = transformService.LonLatConvertToLambert(dmDotJW.x, dmDotJW.y);
                        if(dmMapCom.pointWithinPolygon(Arrays.asList(points),dmDotLb.x,dmDotLb.y)){
                            result += "{";
                            result += "\"dmgisId\":\"" + city.getId() + "\",";
                            result += "\"stationName\":\"" + city.getVillagename() + "\",";
                            result += "\"population\":\"" + city.getPopulation() + "\",";
                            result += "\"mayor\":\"" + city.getVillagehead() + "\",";
                            result += "\"tel\":\"" + city.getContacttel() + "\",";
                            result += "\"lon\":" + city.getLon() + ",";
                            result += "\"lat\":" + city.getLat() + ",";
                            result += "\"county\":\"" + city.getCountry() + "\"";
                            result += "},";
                        }
                    }
                } catch (Exception e) {
                    System.err.println(e.getStackTrace());
                }
            }
        }
        if (result.endsWith(",")) {
            result = result.substring(0, result.length() - 1);
        }
        result = result + "]";
        return result;
    }

    /* 得到山洪预警文档描述 */
    @RequestMapping("/getSLWarning")
    @ResponseBody
    public Object getSLWarning(HttpServletRequest request, Model model) throws Exception {
        List<sl_warning> resultList = forecastInfoService.getSLWarning(); //
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        resultList.get(0).setTime(simpleDateFormat.format(resultList.get(0).getDatechar()));
        return resultList;
    }

    @RequestMapping("/getSLAreaDoc")
    @ResponseBody
    public Object getDZAreaDoc(HttpServletRequest request, Model model) throws Exception {
        String docid = request.getParameter("docid");
        List<DZWarning> result = forecastInfoService.getDZAreaDoc(docid);
        // 兰伯特转经纬度
        for (DZWarning dzWarning : result) {
            if (dzWarning.getGradeArea2() != null && !dzWarning.getGradeArea2().equals("")) {
                dzWarning.setWarLevel("蓝色预警");
            }
            if (dzWarning.getGradeArea3() != null && !dzWarning.getGradeArea3().equals("")) {
                dzWarning.setWarLevel("黄色预警");
            }
            if (dzWarning.getGradeArea4() != null && !dzWarning.getGradeArea4().equals("")) {
                dzWarning.setWarLevel("橙色预警");
            }
            if (dzWarning.getGradeArea5() != null && !dzWarning.getGradeArea5().equals("")) {
                dzWarning.setWarLevel("红色预警");
            }
            ArrayList<CEntity> cEntities = new ArrayList<CEntity>();
            if (!StringUtil.IsNullOrEmpty(dzWarning.getPos())) {
                String[] posArr = dzWarning.getPos().split("\\*");
                for (String pos : posArr) {
                    try {
                        if (pos == null || pos.equals("")) {
                            continue;
                        }
                        CEntity cEntity = new CEntity();
                        ArrayList<MyPoint> tempPos = new ArrayList<MyPoint>();
                        String strColor = pos.split("#")[0];
                        // 16进制颜色
                        cEntity.setColor(strColor);
                        String[] dotset = pos.split("#")[1].split(",");
                        int ii = 0;
                        for (String strDot : dotset) {
                            String[] dot = strDot.split(" ");
                            DmMapPoint dmDot = new DmMapPoint(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                            DmMapPoint ltDot = transformService.LambertConvertToLonLat(dmDot.x, dmDot.y);
                            MyPoint dm = new MyPoint(ltDot.x, ltDot.y);
                            tempPos.add(dm);
                            ii++;
                        }
                        cEntity.setPosArr(tempPos);
                        cEntities.add(cEntity);
                    } catch (Exception e) {
                        System.err.println(e.getStackTrace());
                    }
                }
                dzWarning.setPos(dzWarning.getPos());
                dzWarning.setEntites(cEntities);
            }

            Date date = dzWarning.getDateChar();
            dzWarning.setDate(new DateTime(date).toDateString());
            dzWarning.setDateChar(null);
            // 文件处理
        }
        return result;
    }

    /**
     * 初始化水情界面
     *
     * @return
     */
    @RequestMapping("/initWaterPage")
    @ResponseBody
    public Object initWaterPage() {
        ArrayList<Object> resultList = new ArrayList<Object>();
        // 时间
        DateTime endTime = new DateTime(forecastInfoService.getWaterNewDate());//
        resultList.add(endTime.AddHours(-1).toDateTimeString());
        resultList.add(endTime.toDateTimeString());
        // 区县
        List<water_station> countyList = forecastInfoService.getWaterSta2();//
        resultList.add(countyList);
        return resultList;
    }

    /**
     * 水情查询
     *
     * @param request
     * @param model
     * @return
     * @throws ParseException
     * @author dsq
     * @date 2018年7月11日
     */
    @RequestMapping("/waterQuery")
    @ResponseBody
    public Object waterQuery(HttpServletRequest request, Model model) throws ParseException {
        String startDate = request.getParameter("startDate");
        String endDate = request.getParameter("endDate");
        String countys = request.getParameter("countys");
        List<water_station> resultList = forecastInfoService.waterQuery(startDate, endDate, countys);
        return resultList;
    }

    /**
     * 初始化水情动态图
     *
     * @return
     * @author dsq
     * @date 2018年7月12日
     */
    @RequestMapping("/initWaterChart")
    @ResponseBody
    public Object initWaterChart() {
        String quyuzhanTongJiList = "";
        List<water_station> townList = forecastInfoService.getWaterSta2();
        quyuzhanTongJiList += "<tr><td width=\"62\" valign='top'><a class=\"black\" style=\"text-decoration:none;\" href=\"javascript:void(0);\">";
        int j = 0;
        quyuzhanTongJiList += "水位站" + "</a></td><td style=\"white-space:normal;\"><br/>";
        for (water_station station : townList) {
            String checkstr = "";
            if (j < 1) {
                checkstr = "checked='checked'";
            }
            if ((j + 1) % 2 == 0) {
                quyuzhanTongJiList += "<input name=\"citys\" " + checkstr + " type=\"radio\" value=\""
                        + station.getStcd() + "\" />" + station.getStnm() + "<br/>";
            } else {
                quyuzhanTongJiList += "<input " + (j == 0 ? "checked" : "") + " name=\"citys\" " + checkstr
                        + " type=\"radio\" value=\"" + station.getStcd() + "\" />"
                        + station.getStnm() + " &nbsp;&nbsp;";
            }
            j++;
        }
        quyuzhanTongJiList += "</td></tr>";
        quyuzhanTongJiList = quyuzhanTongJiList.replaceFirst("<br/>", "");
        return quyuzhanTongJiList;
    }

    /**
     * 添加水位动态图
     *
     * @param request
     */
    @RequestMapping("/addWaterChart")
    @ResponseBody
    public Object addWaterChart(HttpServletRequest request, Model model) throws ParseException {
        Date startDate = DateTime.parseDateTime(request.getParameter("startDate")).toDate();
        Date endDate = DateTime.parseDateTime(request.getParameter("endDate")).toDate();
        String[] stations = request.getParameterValues("citys");
        String chartType = request.getParameter("chartType");
        ActualElemQuery elemQuery = new ActualElemQuery();
        elemQuery.setStations(Arrays.asList(stations));
        elemQuery.setStartDate(startDate);
        elemQuery.setEndDate(endDate);
        elemQuery.setType(chartType);
        List<water> resultList = forecastInfoService.qxWaterQuery(elemQuery);
        // 处理成曲线图
        List<String> hours = new ArrayList<String>();
        Map<String, List<Double>> stationValMap = new HashMap<String, List<Double>>();
        for (water actualData : resultList) {
            String stationName = actualData.getStationname().trim();
            if (stationName.equals(resultList.get(0).getStationname().trim())) {
                hours.add(new DateTime(actualData.getLatestobservetime()).GetHour() + ":" + new DateTime(actualData.getLatestobservetime()).GetMinute());
            }
            if (!stationValMap.keySet().contains(stationName)) {
                List<Double> values = new ArrayList<Double>();
                values.add(actualData.getSmallscalewaterstatus());
                stationValMap.put(stationName, values);
            } else {
                stationValMap.get(stationName).add(actualData.getSmallscalewaterstatus());
            }
        }
        ArrayList<Object> result = new ArrayList<Object>();
        result.add(hours);
        for (String key : stationValMap.keySet()) {
            ArrayList<Object> tempArr = new ArrayList<Object>();
            tempArr.add(key);
            tempArr.add(stationValMap.get(key));
            result.add(tempArr);
        }
        return result;
    }

    /**
     * 水情查询
     *
     * @param request
     * @param model
     */
    @RequestMapping("/firstwaterQuery")
    @ResponseBody
    public Object firstWaterQuery(HttpServletRequest request, Model model) throws ParseException {
        List<water> resultList = forecastInfoService.firstWaterQuery();
        return resultList;
    }


    /**
     * 获取气象监控信息
     *
     * @return
     * @throws Exception
     * @author dsq
     * @date 2018年8月20日
     */
    @RequestMapping("/getQxElemMoniData")
    @ResponseBody
    public Object getQxElemMoniData() throws Exception {
        String hour = configService.getSysConfig("气象要素").get(0).getParamvalue();
        if (StringUtil.IsNullOrEmpty(hour)) {
            hour = "24";
        }
        List<warn_moni_info> warnList = guoTuService.getQxElemMoniData(Integer.parseInt(hour));
        List<SmallScaleStation> stationList = configService.getTownStaList();
        List<QxElemMoniData> resultList = new ArrayList<QxElemMoniData>();
        for (warn_moni_info moni_info : warnList) {
            for (SmallScaleStation station : stationList) {
                if (moni_info.getStationid().equals(station.getStationID())) {
                    QxElemMoniData moniData = new QxElemMoniData();
                    moniData.setId(moni_info.getId());
                    moniData.setStationid(moni_info.getStationid());
                    moniData.setLon(station.getLongitude());
                    moniData.setLat(station.getLatitude());
                    DmMapPoint dmDot = new DmMapPoint(station.getLongitude(), station.getLatitude());
                    DmMapPoint ltDot = transformService.LambertConvertToLonLat(dmDot.x, dmDot.y);
                    moniData.setX(ltDot.x);
                    moniData.setY(ltDot.y);
                    moniData.setMonitorvalue(moni_info.getMonitorvalue());
                    moniData.setStationName(station.getStationName());
                    moniData.setWarningtime(new DateTime(moni_info.getWarningtime()).toDateTimeString());
                    moniData.setWarningtype(moni_info.getWarningtype());
                    resultList.add(moniData);
                }

            }
        }
        // 获取预警监控信息
        return resultList;
    }

    /**
     * 获取雷达监控信息
     *
     * @return
     * @throws Exception
     * @author dsq
     * @date 2018年8月20日
     */
    @RequestMapping("/getRadarMoniData")
    @ResponseBody
    public Object getRadarMoniData(HttpServletRequest request, Model model) throws Exception {
        List<radar_warn_monitor_info> warnList = guoTuService.getRadarMoniData(3);
        List<RadarMoniData> resultList = new ArrayList<RadarMoniData>();
        String urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\radar\\";
        FileUtil.mkDirs(urlpath);// 创建文件夹
        // 当图片达到1000张时清除
        FileUtil.ClearTempFiles(urlpath, 1000);
        for (radar_warn_monitor_info moniInfo : warnList) {
            RadarMoniData moniData = new RadarMoniData();
            moniData.setElevationangle(moniInfo.getElevationangle());
            moniData.setRadarstationid(moniInfo.getRadarstationid());
            moniData.setType(moniInfo.getType());
            moniData.setWarningtime(new DateTime(moniInfo.getWarningtime()).toDateString());
            // 处理文件地址
            String filePath = moniInfo.getFilepath();
            String fileName = filePath.split("\\\\")[filePath.split("\\\\").length - 1] + ".png";
            String servicePath = urlpath + fileName;
            File serviceFile = new File(servicePath);
            if (serviceFile.exists()) {
                moniData.setFilepath("Temp\\radar\\" + fileName);
            } else {
                // 从mongdb获取图片
                Map<String, Object> map = new HashMap<String, Object>();
                String datechar = fileName.split("\\.")[0];
                String timechar = fileName.split("\\.")[1];
                datechar = datechar.substring(0, 4) + "-" + datechar.substring(4, 6) + "-" + datechar.substring(6, 8)
                        + " " + timechar.substring(0, 2) + ":" + timechar.substring(2, 4) + ":00";
                DateTime radarDate = DateTime.parseDateTime(datechar).AddHours(8);
                map.put("datechar", radarDate.toDateString());
                map.put("stationid", moniInfo.getRadarstationid());
                map.put("elevation", String.valueOf(moniData.getElevationangle()));
                map.put("ldtype", moniData.getType());
                map.put("timechar", timechar.substring(0, 3));
                map.put("collectionName", "ld_png_file");
                map.put("advCode", DbConfig.advCode);
                byte[] data = ms.selectData(map);
                FileUtil.bytesToFile(data, servicePath);
                moniData.setFilepath("Temp\\radar\\" + fileName);
            }
            // 处理雷达图预警区域
            String[] warnArea = moniInfo.getWarningarea().split("\\*")[0].split(",");
            double[] pos = new double[warnArea.length];
            for (int i = 0; i < warnArea.length; i += 2) {
                DmMapPoint dmDot = new DmMapPoint(Double.parseDouble(warnArea[i]), Double.parseDouble(warnArea[i + 1]));
                DmMapPoint ltDot = transformService.LambertConvertToLonLat(dmDot.x, dmDot.y);
                pos[i] = ltDot.x;
                pos[i + 1] = ltDot.y;
            }
            moniData.setWarningarea(pos);
            resultList.add(moniData);
        }
        // 获取预警监控信息
        return resultList;
    }

    /**
     * 查询地灾隐患点
     *
     * @param request
     * @param model
     * @return
     * @author dsq
     * @date 2018年7月27日
     */
    @RequestMapping("getDisPoint")
    @ResponseBody
    public Object getDisPoint(HttpServletRequest request, Model model) {
        String disId = request.getParameter("disId");
        String disName = request.getParameter("disName");
        String county = request.getParameter("county");
        String disType = request.getParameter("disType");
        String level = request.getParameter("level");
        String disLevel = request.getParameter("disLevel");
        String population = request.getParameter("population");
        String populationTo = request.getParameter("populationTo");
        String property = request.getParameter("property");
        String propertyTo = request.getParameter("propertyTo");
        DisPointSearch disPointSearch = new DisPointSearch();
        disPointSearch.setDisId(disId);
        disPointSearch.setDisName(disName);
        disPointSearch.setCounty(StringUtil.ParseNull(county));
        disPointSearch.setDisType(StringUtil.ParseNull(disType));
        disPointSearch.setLevel(StringUtil.ParseNull(level));
        disPointSearch.setDisLevel(StringUtil.ParseNull(disLevel));
        if (!(StringUtil.IsNullOrEmpty(population) || StringUtil.IsNullOrEmpty(populationTo))) {
            disPointSearch.setPopulation(Integer.parseInt(population));
            disPointSearch.setPopulationTo(Integer.parseInt(populationTo));
        }
        if (!(StringUtil.IsNullOrEmpty(property) || StringUtil.IsNullOrEmpty(propertyTo))) {
            disPointSearch.setProperty(Integer.parseInt(property));
            disPointSearch.setPropertyTo(Integer.parseInt(propertyTo));
        }
        List<potential_points> disPoints = guoTuService.selectDisPoint(disPointSearch);
        List<DPoint> resultList = new ArrayList<DPoint>();
        for (int i = 0; i < disPoints.toArray().length; i++) {
            DmMapPoint dt = new DmMapPoint();
            Double lon = WebCtrlData.Getddformddffmm(Double.parseDouble(disPoints.get(i).getLon().toString()));
            Double lat = WebCtrlData.Getddformddffmm(Double.parseDouble(disPoints.get(i).getLat().toString()));
            dt = transformService.LonLatConvertToLambert(lon, lat);
            disPoints.get(i).setX((float) dt.x);
            disPoints.get(i).setY((float) dt.y);
            DPoint dPoint = new DPoint();
            dPoint.setLon(lon);
            dPoint.setLat(lat);
            dPoint.setStationName(disPoints.get(i).getPp_name());
            dPoint.setPp_name(disPoints.get(i).getPp_name());
            dPoint.setDis_type(disPoints.get(i).getDis_type());
            dPoint.setDis_level(disPoints.get(i).getDis_level());
            dPoint.setDanger_level(disPoints.get(i).getDanger_level());
            dPoint.setThreat_pop(disPoints.get(i).getThreat_pop());
            dPoint.setThreat_prop(disPoints.get(i).getThreat_prop());
            dPoint.setContact(disPoints.get(i).getContact());
            dPoint.setContact_tel(disPoints.get(i).getContact_tel());
            dPoint.setContact1(disPoints.get(i).getContact1());
            dPoint.setContact1_tel(disPoints.get(i).getContact1_tel());
            resultList.add(dPoint);
        }
        return resultList;
    }


    /**
     * 获取应急点
     *
     * @param
     * @return
     * @author ymf
     * @date 2019/9/18
     **/
    @RequestMapping("/Empoint")
    @ResponseBody
    public Object getEmpoint(HttpServletRequest request, Model model) {
        String startDate = request.getParameter("startDate") + ":00:00";
        ;
        String endDate = request.getParameter("endDate") + ":59:59";
        ;
        DZQuery dzQuery = new DZQuery();
        dzQuery.setStartDate(startDate);
        dzQuery.setEndDate(endDate);
        List<Emergency> empoint = forecastInfoService.getEmpoint(dzQuery);
        return empoint;
    }


    /* 汇水区实况面雨量分析 */
  /*  @RequestMapping("/getArealrainfall")
    @ResponseBody
    public Object getArealRainfall(HttpServletRequest request, Model model) throws Exception {
        SRainfallSearch selectKey = new SRainfallSearch();// 查询类
        String startDate = request.getParameter("startDate") + ":00:00";// 开始时间
        String endDate = request.getParameter("endDate") + ":00:00";// 结束时间
        selectKey.setStartDate(startDate);
        List<SysConfig> result1 = warnQueryService.GetCatchmentarea();
        String poss = result1.get(0).getParamValue();

        String[] posArr = poss.split("\\*");

        List<MsgMediumSmallScale> msgList = new ArrayList<MsgMediumSmallScale>();
        if (endDate.contains("null:00:00")) {
            msgList = forecastInfoService.getDSumRain(selectKey);// 雨量
        } else {
            selectKey.setEndDate(endDate);
            msgList = forecastInfoService.getSumRain(selectKey);// 雨量
        }
        List<SurfaceRainResult> resultList = new ArrayList<SurfaceRainResult>();// 最终结果
        List<SurfaceRainResult> resultList1 = new ArrayList<SurfaceRainResult>();// 最终结果
        Double surfacerains = 0.0;
        for (String rainwater : posArr) {
            String[] strdata = rainwater.split(",");
            String[] resultArr = new String[strdata.length * 2];
            for (int i = 0; i < strdata.length; i++) {
                resultArr[2 * i] = strdata[i].split(" ")[0];
                resultArr[2 * i + 1] = strdata[i].split(" ")[1];
            }
            int ii = 0;
            double xval = 0.0;
            double yval = 0.0;
            Integer index = 0;
            DmMapPoint[] dt = new DmMapPoint[resultArr.length / 2];
            for (int i = 0; i < resultArr.length / 2; i++) {
                xval = Double.parseDouble(resultArr[2 * i]);
                yval = Double.parseDouble(resultArr[2 * i + 1]);
                DmMapPoint DmDot2 = new DmMapPoint(xval, yval);
                dt[index] = DmDot2;
                index++;
                ii++;
            }
            SurfaceRainResult result = new SurfaceRainResult();
            String name = "实时面雨量";
            Double lon = 112.869329;
            Double lat = 27.900990;
            result.setName(name);
            result.setLon(lon);
            result.setLat(lat);
            DmMapPoint dmDot = new DmMapPoint(lon, lat);
            DmMapPoint ltDot = new DmMapPoint(dmDot.x, dmDot.y);
            result.setX(ltDot.x);
            result.setY(ltDot.y);

            Tin dcontour = new Tin();
            boolean isOn = false;
            for (MsgMediumSmallScale msg : msgList) {
                DmMapPoint dmDotJW = new DmMapPoint(msg.getLon(), msg.getLat());
                DmMapPoint dmDotLb = transformService.LonLatConvertToLambert(dmDotJW.x, dmDotJW.y);
                MapCommon dmMapCom = new MapCommon();
                if(dmMapCom.pointWithinPolygon(Arrays.asList(dt),dmDotLb.x,dmDotLb.y)){
                    dcontour.addpoint(dmDotLb.x, dmDotLb.y, msg.getAmassRain());
                    isOn = true;
                }
            }
            if (isOn) {
                DmMapRectangle rct = getObjRect(dt);
                rct.minx = (rct.minx -(rct.maxx-rct.minx));
                rct.maxx = (rct.maxx-(rct.maxx-rct.minx));
                rct.miny = (rct.miny-(rct.maxy-rct.miny));
                rct.maxy = (rct.maxy-(rct.maxy-rct.miny));
                dcontour.calculate4pintzvalue(rc);
                dcontour.dmmesh();
                surfacerains = dcontour.getarearain1(dpart, (short) 1);
            } else {
                surfacerains = 99999.0;
            }
            DecimalFormat df = new DecimalFormat("#.00");
            result.setSurfacerain(Float.parseFloat(df.format(surfacerains)));
            resultList.add(result);
        }
        SurfaceRainResult surfaceRainResult = resultList.get(5);
        resultList1.add(surfaceRainResult);

        return resultList1;
    }*/


    /* 汇水区预报面雨量分析 */
   /* @RequestMapping("/getYBArealrainfall")
    @ResponseBody
    public Object getYBArealRainfall(HttpServletRequest request, Model model) throws Exception {
        TownshipForecastKey selectKey = new TownshipForecastKey();// 查询类
        String time = request.getParameter("date");// 时间
        String sx = request.getParameter("sx");// 时效
        int nTimes;
        List<CityFcstInfo> cityresult = new ArrayList<CityFcstInfo>();// 城市预报结果
        try {
            nTimes = Integer.parseInt(sx);
            selectKey.setNTimes(nTimes);
            selectKey.setDateChar(DateTime.parseDate(time).toDate());
            List<TownshipForecast> fcstList = forecastInfoService.getYBRainfall(selectKey);
            int count = fcstList.toArray().length;
            for (int i = 0; i < count; i++) {
                CityFcstInfo fcstInfo = new CityFcstInfo();
                fcstInfo.setRain(fcstList.get(i).getRain());
                fcstInfo.setLat(fcstList.get(i).getLatitude());
                fcstInfo.setLon(fcstList.get(i).getLongitude());
                fcstInfo.setStationName(fcstList.get(i).getStationName());
                cityresult.add(fcstInfo);
            }
        } catch (Exception e) {
            // TODO: 城镇预报查询异常
            logger.error(e);
        }


        List<SysConfig> result1 = warnQueryService.GetCatchmentarea();
        String poss = result1.get(0).getParamValue();

        String[] posArr = poss.split("\\*");


        List<SurfaceRainResult> resultList = new ArrayList<SurfaceRainResult>();// 最终结果
        List<SurfaceRainResult> resultList1 = new ArrayList<SurfaceRainResult>();// 最终结果
        Double surfacerains = 0.0;
        if (cityresult.size() > 0 && cityresult != null) {
            for (String rainwater : posArr) {

                String[] strdata = rainwater.split(",");
                String[] resultArr = new String[strdata.length * 2];
                for (int i = 0; i < strdata.length; i++) {
                    resultArr[2 * i] = strdata[i].split(" ")[0];
                    resultArr[2 * i + 1] = strdata[i].split(" ")[1];
                }
                int ii = 0;
                double xval = 0.0;
                double yval = 0.0;
                Integer index = 0;
                DmMapPoint[] dt = new DmMapPoint[resultArr.length / 2];
                for (int i = 0; i < resultArr.length / 2; i++) {
                    xval = Double.parseDouble(resultArr[2 * i]);
                    yval = Double.parseDouble(resultArr[2 * i + 1]);
                    DmMapPoint DmDot2 = new DmMapPoint(xval, yval);
                    dt[index] = DmDot2;
                    index++;
                    ii++;
                }
                String names = "";
                SurfaceRainResult result = new SurfaceRainResult();
                String name = "预报面雨量";
                Double lon = 112.869329;
                Double lat = 27.900990;
                result.setName(name);
                result.setLon(lon);
                result.setLat(lat);
                DmMapPoint dmDot = new DmMapPoint(lon, lat);
                DmMapPoint ltDot = new DmMapPoint(dmDot.x, dmDot.y);
                result.setX(ltDot.x);
                result.setY(ltDot.y);
                Tin dcontour = new Tin();
                boolean isOn = false;
                for (CityFcstInfo city : cityresult) {
                    DmMapPoint dmDotJW = new DmMapPoint(city.getLon(), city.getLat());
                    DmMapPoint dmDotLb = transformService.LonLatConvertToLambert(dmDotJW.x, dmDotJW.y);
                    MapCommon dmMapCom = new MapCommon();
                    if(dmMapCom.pointWithinPolygon(Arrays.asList(points),dmDotLb.x,dmDotLb.y)){
                        dcontour.addpoint(dmDotLb.x, dmDotLb.y, city.getRain());
                        isOn = true;
                    }
                }
                if (isOn) {
                    DmMapRectangle rct = getObjRect(dt);
                    rct.minx = (rct.minx -(rct.maxx-rct.minx));
                    rct.maxx = (rct.maxx-(rct.maxx-rct.minx));
                    rct.miny = (rct.miny-(rct.maxy-rct.miny));
                    rct.maxy = (rct.maxy-(rct.maxy-rct.miny));
                    dcontour.calculate4pintzvalue(rc);
                    dcontour.dmmesh();
                    surfacerains = dcontour.getarearain1(dpart, (short) 1);
                } else {
                    surfacerains = 99999.0;
                }
                DecimalFormat df = new DecimalFormat("#.00");
                result.setSurfacerain(Float.parseFloat(df.format(surfacerains)));
                resultList.add(result);
            }
            SurfaceRainResult surfaceRainResult = resultList.get(5);
            resultList1.add(surfaceRainResult);
        }

        return resultList1;
    }*/


    /* 得到水库入库流量预报文档 */
    @RequestMapping("/getInputFlowDoc")
    @ResponseBody
    public Object getInputFlowDoc(HttpServletRequest request, Model model) throws ParseException {
        String datechar = request.getParameter("datechar");// 获取预报日期
        String timechar = request.getParameter("timechar");// 获取预报时次
        //String ntimes = request.getParameter("ntimes");// 获取预报时效
        //入库流量2020051708.doc
        String docName = "入库流量" + datechar.replaceAll("-", "") + timechar + ".doc";
        String id = forecastInfoService.getProductID(docName);// 获取编号
        String urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\InputFlowFcst\\";// 临时文件目录

        FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
        FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存

        String fileName = docName.split("\\\\")[docName.split("\\\\").length - 1];// 文件名
        String doctype = fileName.split("\\.")[fileName.split("\\.").length - 1];// 文件类型
        String servicePath = "";// 服务器文件
        if (doctype.contains("doc")) {
            String pdfPath = urlpath + fileName.replace(doctype, "pdf");
            File pdfFile = new File(pdfPath);
            if (pdfFile.exists()) {
                servicePath = "Temp\\InputFlowFcst\\" + fileName.replace(doctype, "pdf");
            } else {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("id", id);
                map.put("table_name", "base_product");
                map.put("collectionName", "pdf_file");
                map.put("advCode", DbConfig.advCode);
                byte[] data = ms.selectData(map);
                // 下载doc文件
                if (data == null) {
                    return "";
                }
                FileUtil.bytesToFile(data, pdfPath);
                servicePath = "Temp\\InputFlowFcst\\" + fileName.replace(doctype, "pdf");
            }
        }
        servicePath = servicePath.replace("\\", "/");
        return servicePath;
    }


    /* 得到水库灌溉等级预报文档 */
    @RequestMapping("/getIrrigationDoc")
    @ResponseBody
    public Object getIrrigationDoc(HttpServletRequest request, Model model) throws ParseException {
        String datechar = request.getParameter("datechar");// 获取预报日期
        String timechar = request.getParameter("timechar");// 获取预报时次
        String ntimes = request.getParameter("ntimes");// 获取预报时效
        //水库灌溉等级预报2020051820_48.doc
        String docName = "水库灌溉等级预报" + datechar.replaceAll("-", "") + timechar + "_" + ntimes + ".doc";
        String id = forecastInfoService.getProductID(docName);// 获取编号
        String urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\IrrigationFcst\\";// 临时文件目录

        FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
        FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存

        String fileName = docName.split("\\\\")[docName.split("\\\\").length - 1];// 文件名
        String doctype = fileName.split("\\.")[fileName.split("\\.").length - 1];// 文件类型
        String servicePath = "";// 服务器文件
        if (doctype.contains("doc")) {
            String pdfPath = urlpath + fileName.replace(doctype, "pdf");
            File pdfFile = new File(pdfPath);
            if (pdfFile.exists()) {
                servicePath = "Temp\\IrrigationFcst\\" + fileName.replace(doctype, "pdf");
            } else {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("id", id);
                map.put("table_name", "base_product");
                map.put("collectionName", "pdf_file");
                map.put("advCode", DbConfig.advCode);
                byte[] data = ms.selectData(map);
                //byte[] data = HttpRequest.get(DbConfig.mongoSelectUrl, map, true).bytes();
                // 下载doc文件
                if (data==null) {
                    return "";
                }
                FileUtil.bytesToFile(data, pdfPath);
                servicePath = "Temp\\IrrigationFcst\\" + fileName.replace(doctype, "pdf");
            }
        }
        servicePath = servicePath.replace("\\", "/");
        return servicePath;
    }

    /*初始化预警信息界面*/
    @RequestMapping("/GetAuditingWarn")
    @ResponseBody
    public Object getAuditingWarn(HttpServletRequest request, Model model) {
        List<sl_warning> sl_warnings = forecastInfoService.getAuditingWarn();
        List<sl_warning> resultList = new ArrayList<sl_warning>();// 主
        int count = sl_warnings.toArray().length;
        for (int i = 0; i < count; i++) {
            ArrayList<Entites> entites = new ArrayList<Entites>();
            if (sl_warnings.get(i).getGradearea2() != null && !sl_warnings.get(i).getGradearea2().equals("")) {
                sl_warnings.get(i).setWaringgrad("蓝色预警");
            }
            if (sl_warnings.get(i).getGradearea3() != null && !sl_warnings.get(i).getGradearea3().equals("")) {
                sl_warnings.get(i).setWaringgrad("黄色预警");
            }
            if (sl_warnings.get(i).getGradearea4() != null && !sl_warnings.get(i).getGradearea4().equals("")) {
                sl_warnings.get(i).setWaringgrad("橙色预警");
            }
            if (sl_warnings.get(i).getGradearea5() != null && !sl_warnings.get(i).getGradearea5().equals("")) {
                sl_warnings.get(i).setWaringgrad("红色预警");
            }
            if (sl_warnings.get(i).getPos() != null) {
                String[] posArr = sl_warnings.get(i).getPos().split("\\*");// 三个部分，*分隔
                for (String pos : posArr) {
                    try {
                        if (pos == null || pos.equals("")) {
                            continue;
                        }
                        Entites entity = new Entites();// 实体类：颜色，坐标
                        ArrayList<MyPoint> tempPos = new ArrayList<MyPoint>();// 临时
                        String strColor = pos.split("#")[0];// #分隔，第一个代表颜色
                        entity.setColor(strColor);// 存入类
                        String[] dotset = pos.split("#")[1].split(",");// 坐标数组
                        int ii = 0;
                        for (String strDot : dotset) {
                            String[] dot = strDot.split(" ");
                            DmMapPoint dmDot = new DmMapPoint(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                            DmMapPoint ltDot = transformService.LambertConvertToLonLat(dmDot.x, dmDot.y);
                            MyPoint dm = new MyPoint(ltDot.x, ltDot.y);
                            tempPos.add(dm);
                            ii++;
                        }
                        entity.setPosArr(tempPos);
                        entites.add(entity);
                    } catch (Exception e) {
                        System.err.println(e.getStackTrace());
                    }
                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Collections.sort(entites, new SortByColor());// 排序
                sl_warning sl_warning = new sl_warning();
                sl_warning.setDocid(sl_warnings.get(i).getDocid());
                sl_warning.setTime(sdf.format(sl_warnings.get(i).getDatechar()));
                sl_warning.setTimechar(sl_warnings.get(i).getTimechar());
                sl_warning.setWarning_id(sl_warnings.get(i).getWarning_id());
                sl_warning.setWarningtype(sl_warnings.get(i).getWarningtype());
                sl_warning.setWaringgrad(sl_warnings.get(i).getWaringgrad());
                sl_warning.setFirst(sl_warnings.get(i).getFirst());
                sl_warning.setPosarea3(sl_warnings.get(i).getPosarea3());
                sl_warning.setPosarea4(sl_warnings.get(i).getPosarea4());
                sl_warning.setPosarea5(sl_warnings.get(i).getPosarea5());
                sl_warning.setPos(sl_warnings.get(i).getPos());
                sl_warning.setEntites(entites);
                resultList.add(sl_warning);
//            }
            }
        }
        return resultList;
    }

    /*得到预警信息*/
    @RequestMapping("/GetWarnmessage")
    @ResponseBody
    public Object getWarnmessage(HttpServletRequest request, Model model) {
        String id = request.getParameter("id");
        List<sl_warning> warnmessage = forecastInfoService.getWarnmessage(id);
        List<sl_warning> resultList = new ArrayList<sl_warning>();// 主
        int count = warnmessage.toArray().length;
        for (int i = 0; i < count; i++) {
            ArrayList<Entites> entites = new ArrayList<Entites>();
            if (warnmessage.get(i).getGradearea2() != null && !warnmessage.get(i).getGradearea2().equals("")) {
                warnmessage.get(i).setWaringgrad("蓝色预警");
            }
            if (warnmessage.get(i).getGradearea3() != null && !warnmessage.get(i).getGradearea3().equals("")) {
                warnmessage.get(i).setWaringgrad("黄色预警");
            }
            if (warnmessage.get(i).getGradearea4() != null && !warnmessage.get(i).getGradearea4().equals("")) {
                warnmessage.get(i).setWaringgrad("橙色预警");
            }
            if (warnmessage.get(i).getGradearea5() != null && !warnmessage.get(i).getGradearea5().equals("")) {
                warnmessage.get(i).setWaringgrad("红色预警");
            }
            if (warnmessage.get(i).getPos() != null) {
                String[] posArr = warnmessage.get(i).getPos().split("\\*");// 三个部分，*分隔
                for (String pos : posArr) {
                    try {
                        if (pos == null || pos.equals("")) {
                            continue;
                        }
                        Entites entity = new Entites();// 实体类：颜色，坐标
                        ArrayList<MyPoint> tempPos = new ArrayList<MyPoint>();// 临时
                        String strColor = pos.split("#")[0];// #分隔，第一个代表颜色
                        entity.setColor(strColor);// 存入类
                        String[] dotset = pos.split("#")[1].split(",");// 坐标数组
                        int ii = 0;
                        for (String strDot : dotset) {
                            String[] dot = strDot.split(" ");
                            DmMapPoint dmDot = new DmMapPoint(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                            DmMapPoint ltDot = transformService.LambertConvertToLonLat(dmDot.x, dmDot.y);
                            MyPoint dm = new MyPoint(ltDot.x, ltDot.y);
                            tempPos.add(dm);
                            ii++;
                        }
                        entity.setPosArr(tempPos);
                        entites.add(entity);
                    } catch (Exception e) {
                        System.err.println(e.getStackTrace());
                    }
                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Collections.sort(entites, new SortByColor());// 排序


                if (warnmessage.get(i).getPosarea3() != null && !warnmessage.get(i).getPosarea3().equals("")) {
                    String reaArrRep = warnmessage.get(i).getPosarea3().replace(".", "");//分割
                    reaArrRep = reaArrRep.replace(DbConfig.CITY+":", "");
                    String[] reaArr = reaArrRep.split(",");
                    for (int j = 0; j < reaArr.length; j++) {
                        sl_warning sl_warning = new sl_warning();
                        sl_warning.setDocid(warnmessage.get(i).getDocid());
                        sl_warning.setTime(sdf.format(warnmessage.get(i).getDatechar()));
                        sl_warning.setTimechar(warnmessage.get(i).getTimechar());
                        sl_warning.setWarning_id(warnmessage.get(i).getWarning_id());
                        sl_warning.setWarningtype(warnmessage.get(i).getWarningtype());
                        sl_warning.setWaringgrad(warnmessage.get(i).getWaringgrad());
                        sl_warning.setFirst(warnmessage.get(i).getFirst());
                        sl_warning.setXz(reaArr[j]);
                        sl_warning.setPos(warnmessage.get(i).getPos());
                        sl_warning.setEntites(entites);
                        resultList.add(sl_warning);
                    }
                }
                if (warnmessage.get(i).getPosarea4() != null && !warnmessage.get(i).getPosarea4().equals("")) {
                    String reaArrRep = warnmessage.get(i).getPosarea4().replace(".", "");//分割
                    reaArrRep = reaArrRep.replace(DbConfig.CITY+":", "");
                    String[] reaArr2 = reaArrRep.split(",");
                    for (int j = 0; j < reaArr2.length; j++) {
                        sl_warning sl_warning = new sl_warning();
                        sl_warning.setDocid(warnmessage.get(i).getDocid());
                        sl_warning.setTime(sdf.format(warnmessage.get(i).getDatechar()));
                        sl_warning.setTimechar(warnmessage.get(i).getTimechar());
                        sl_warning.setWarning_id(warnmessage.get(i).getWarning_id());
                        sl_warning.setWarningtype(warnmessage.get(i).getWarningtype());
                        sl_warning.setWaringgrad(warnmessage.get(i).getWaringgrad());
                        sl_warning.setFirst(warnmessage.get(i).getFirst());
                        sl_warning.setXz(reaArr2[j]);
                        sl_warning.setPos(warnmessage.get(i).getPos());
                        sl_warning.setEntites(entites);
                        resultList.add(sl_warning);
                    }
                }
                if (warnmessage.get(i).getPosarea5() != null && !warnmessage.get(i).getPosarea5().equals("")) {
                    String reaArrRep = warnmessage.get(i).getPosarea5().replace(".", "");//分割
                    reaArrRep = reaArrRep.replace(DbConfig.CITY+":", "");
                    String[] reaArr3 = reaArrRep.split(",");
                    for (int j = 0; j < reaArr3.length; j++) {
                        sl_warning sl_warning = new sl_warning();
                        sl_warning.setDocid(warnmessage.get(i).getDocid());
                        sl_warning.setTime(sdf.format(warnmessage.get(i).getDatechar()));
                        sl_warning.setTimechar(warnmessage.get(i).getTimechar());
                        sl_warning.setWarning_id(warnmessage.get(i).getWarning_id());
                        sl_warning.setWarningtype(warnmessage.get(i).getWarningtype());
                        sl_warning.setWaringgrad(warnmessage.get(i).getWaringgrad());
                        sl_warning.setFirst(warnmessage.get(i).getFirst());
                        sl_warning.setXz(reaArr3[j]);
                        sl_warning.setPos(warnmessage.get(i).getPos());
                        sl_warning.setEntites(entites);

                        resultList.add(sl_warning);
                    }
                }

            }
        }
        return resultList;
    }

    /*更新审核意见*/

    @RequestMapping("/UpdOpinion")
    @ResponseBody
    public Object updOpinion(HttpServletRequest request, Model model) {
        sl_warning sl_warning = new sl_warning();
        String id = request.getParameter("id");//获取id
        String state = request.getParameter("state");// 获取审核状态 0:未审批 1:驳回 2:通过
        String shideas = request.getParameter("shideas");// 获取审核意见
        sl_warning.setShideas(shideas);
        sl_warning.setState(Integer.parseInt(state));
        String resultList = forecastInfoService.updOpinion(sl_warning, id);
        return resultList;
    }

    /***
     * 获取预警信号  当天
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/GetWarnSignalInfo")
    @ResponseBody
    public Object GetWarnSignalInfo(HttpServletRequest request, Model model) {
        List<Object> rltList = new ArrayList<>();
        Object list = forecastInfoService.GetWarnSignalInfo();
        rltList.add(list);
        String stationname = request.getParameter("stationname");//站点名称
        if (!StringUtil.IsNullOrEmpty(stationname) && stationname.endsWith("水库"))
            stationname.substring(0, stationname.length() - 2);
        Object list1 = forecastInfoService.GetWaterWarnMoniInfo(stationname);
        rltList.add(list1);

        Object list2 = forecastInfoService.GetRiverWarnMoniInfo();
        rltList.add(list2);
        return rltList;
    }

    /***
     * 初始化城镇预报界面 */
    @RequestMapping("/InitCityMaxTime")
    @ResponseBody
    public Object InitCityMaxTime(HttpServletRequest request, Model model) {
        String name = request.getParameter("reservoirname");//type角色名称，水利局用户以及非水利局用户
        String county = request.getParameter("county");
        forecastinfotemp infotemp = forecastInfoService.getInitCityMaxTime(name, county);
        String timechar = "";
        String datechar = "";
        String timeTemp = "";
        // 加载列表
        if (infotemp != null) {
            timechar = infotemp.getTimechar().trim();
            datechar = new DateTime(infotemp.getDatechar()).toDateString().trim();// 将日期转换为字符串格式
            timeTemp = "{\"newDate\":\"" + datechar.trim() + "\",\"newTime\":\"" + timechar.trim() + "\"}";
        } else {
            timeTemp = "{}";
        }
        List<township_station> townshipstation = forecastInfoService.getloadCityStation();
        String stationTemp = "[";
        // 加载列表
        if (townshipstation != null) {
            List<StationInfo> listResult = new ArrayList<StationInfo>();
            for (township_station ts : townshipstation) {
                StationInfo station = new StationInfo();
                station.setStationID(ts.getStationid());
                station.setStationName(ts.getStationname());
                listResult.add(station);
            }
            for (StationInfo sta : listResult) {
                stationTemp += "{";
                stationTemp += "\"stationID\":\"" + sta.getStationID() + "\",";
                stationTemp += "\"stationName\":\"" + sta.getStationName() + "\"";
                stationTemp += "},";
            }
            stationTemp = stationTemp.substring(0, stationTemp.length() - 1) + "]";
        } else {
            stationTemp = "[]";
        }
        ArrayList<String> result = new ArrayList<String>();
        result.add(timeTemp);
        result.add(stationTemp);
        return result;
    }

    /***
     * 城镇预报查询
     * @param request
     * @param model
     * @return
     * @throws ParseException
     */

    @RequestMapping("/CityForecast")
    @ResponseBody
    public Object getCityForecast(HttpServletRequest request, Model model) throws Exception {
        String stationname = request.getParameter("reservoirname");
        List<forecastinfotemp> resultList = new ArrayList<>();
        String strDate = request.getParameter("date");// 时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        DateTime dateTime = new DateTime(sdf.parse(strDate));
        String strTime = request.getParameter("sc");// 时次
        String stationID = request.getParameter("stationID");// 类型
        String temp = "";
        if (!stationname.equals("")) {
            forecastinfotemp selectKey = new forecastinfotemp();// 查询类
            selectKey.setDatechar(DateTime.parseDate(strDate).toDate());
            selectKey.setTimechar(strTime);
            selectKey.setStationid(stationID);
            resultList = forecastInfoService.getCityForecast(selectKey, "");
            WebCtrlData wcd = new WebCtrlData();
            temp = "[";
            if (resultList != null) {
                String xValue = "[";
                String yValue = "[";
                String yValue1 = "[";
                List<Forecast> listResult = new ArrayList<Forecast>();
                for (forecastinfotemp fit : resultList) {
                    String strforcastSx = fit.getNtimes().toString().trim();
                    DateTime date = dateTime.AddHours(Integer.parseInt(strforcastSx) - 12);

                    SimpleDateFormat dateFm = new SimpleDateFormat("EEEE");
                    String week = dateFm.format(date.toDate());

                    String strDateTime = date.GetDay() + "日";
                    String day = date.GetDay() + "日";


                    String strWeather1 = "";
                    strWeather1 = String.format("%02d", Integer.parseInt(WebCtrlData.WeatherNameToPicPath(fit.getWeather1().toString())));
                    String strWeather2 = "";
                    strWeather2 = String.format("%02d", Integer.parseInt(WebCtrlData.WeatherNameToPicPath(fit.getWeather2().toString())));


                    String strWeatherDisp = "";
                    if (strWeather1.equals("-65535")) {
                        strWeather1 = "00";
                    }
                    if (strWeather2.equals("-65535")) {
                        strWeather2 = "00";
                    }
                    if (strWeather1.equals(strWeather2))
                        strWeatherDisp = wcd.GetWeatherTq(strWeather1).toString();
                    else
                        strWeatherDisp = wcd.GetWeatherTq(strWeather1).toString() + "</br>转"
                                + wcd.GetWeatherTq(strWeather2).toString();


                    strWeather1 = wcd.GetWeatherTq(strWeather1).toString();
                    strWeather2 = wcd.GetWeatherTq(strWeather2).toString();

                    String weatherCode1 = WebCtrlData.WeatherNameToPicPath(strWeather1);
                    String weatherCode2 = WebCtrlData.WeatherNameToPicPath(strWeather2);

                    String strImgPic1 = "<img height='32' width='32' src='images/weatherDay/" + weatherCode1 + ".gif'>";
                    String strImgPic2 = "<img height='32' width='32' src='images/weatherNight/" + weatherCode2
                            + ".gif'>";

                    String strMinTemp = fit.getMintemp().toString().trim();
                    String strMaxTemp = fit.getMaxtemp().toString().trim();
                    if (strMinTemp.equals("-65535.0") || strMinTemp.equals("65535.0")) {
                        strMinTemp = "";
                    }
                    if (strMaxTemp.equals("-65535.0") || strMaxTemp.equals("65535.0")) {
                        strMaxTemp = "";
                    }
                    String strWindDir1 = "";
                    String strWindDir2 = "";
                    try {
                        strWindDir1 = wcd.GetWeatherFx(String.format("%d", fit.getWindd1())).toString();
                        strWindDir2 = wcd.GetWeatherFx(String.format("%d", fit.getWindd1())).toString();
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }

                    if (!strWindDir1.equals(strWindDir2))
                        strWindDir1 = strWindDir1 + "</br>转" + strWindDir2;

                    int minWind = Integer.parseInt(fit.getWind2().toString().substring(0, 1).trim());
                    String minWindS = String.format("%02d", minWind);

                    int maxWind = Integer.parseInt(fit.getWind1().toString().substring(0, 1).trim());
                    String maxWindS = String.format("%02d", maxWind);
                    String strWindDisp = "";
                    if (minWindS.equals(maxWindS))
                        strWindDisp = wcd
                                .GetWeatherFs(String.valueOf(WebCtrlData.FengSuToFengJi(Double.parseDouble(minWindS))))
                                .toString();
                    else
                        strWindDisp = wcd
                                .GetWeatherFs(String.valueOf(WebCtrlData.FengSuToFengJi(Double.parseDouble(minWindS))))
                                .toString() + " </br>转 "
                                + wcd.GetWeatherFs(String.valueOf(WebCtrlData.FengSuToFengJi(Double.parseDouble(maxWindS))))
                                .toString();
                    String strRain = fit.getRain().toString().trim();
                    String strHumid = fit.getMaxhumid().toString().trim();
                    if (strRain.equals("-65535.0") || strRain.equals("65535.0")) {
                        strRain = "";
                    }
                    if (strHumid.equals("-65535.0") || strHumid.equals("65535.0")) {
                        strHumid = "";
                    }
                    Forecast f = new Forecast();
                    f.setDateTime(strDateTime);
                    f.setDay(day);
                    f.setWeek(week);
                    f.setWeatherPhenomena(strWeatherDisp);
                    f.setStrWeather1(strWeather1);
                    f.setStrWeather2(strWeather2);
                    f.setMaxTemp(strMaxTemp);
                    f.setMinTemp(strMinTemp);
                    f.setWindD(strWindDir1);
                    f.setWindV(strWindDisp);
                    f.setWeatherPic1(strImgPic1);
                    f.setWeatherPic2(strImgPic2);
                    f.setRain(strRain);
                    f.setMaxhumid(strHumid);
                    listResult.add(f);

                    xValue += "'" + strDateTime + "',";
                    yValue += strMaxTemp + ",";
                    yValue1 += strMinTemp + ",";
                }

                String tableData = "[";
                for (Forecast forecast : listResult) {
                    tableData += "{";
                    tableData += "\"dateTime\":\"" + forecast.getDateTime() + "\",";
                    tableData += "\"maxTemp\":\"" + forecast.getMaxTemp() + "\",";
                    tableData += "\"minTemp\":\"" + forecast.getMinTemp() + "\",";
                    tableData += "\"windD\":\"" + forecast.getWindD() + "\",";
                    tableData += "\"windV\":\"" + forecast.getWindV() + "\",";
                    tableData += "\"rain\":\"" + forecast.getRain() + "\",";
                    tableData += "\"humid\":\"" + forecast.getMaxhumid() + "\",";
                    tableData += "\"weatherPic1\":\"" + forecast.getWeatherPic1() + "\",";
                    tableData += "\"weatherPic2\":\"" + forecast.getWeatherPic2() + "\",";
                    tableData += "\"weatherPhenomena\":\"" + forecast.getWeatherPhenomena() + "\",";
                    tableData += "\"strWeather1\":\"" + forecast.getStrWeather1() + "\",";
                    tableData += "\"strWeather2\":\"" + forecast.getStrWeather2() + "\",";
                    tableData += "\"week\":\"" + forecast.getWeek() + "\",";
                    tableData += "\"day\":\"" + forecast.getDay() + "\"";
                    tableData += "},";
                    tableData += "{";
                    tableData += "\"dateTime\":\"" + forecast.getDateTime() + "\",";
                    tableData += "\"maxTemp\":\"" + forecast.getMaxTemp() + "\",";
                    tableData += "\"minTemp\":\"" + forecast.getMinTemp() + "\",";
                    tableData += "\"windD\":\"" + forecast.getWindD() + "\",";
                    tableData += "\"windV\":\"" + forecast.getWindV() + "\",";
                    tableData += "\"rain\":\"" + forecast.getRain() + "\",";
                    tableData += "\"humid\":\"" + forecast.getMaxhumid() + "\",";
                    tableData += "\"weatherPic1\":\"" + forecast.getWeatherPic2() + "\",";
                    tableData += "\"weatherPic2\":\"" + forecast.getWeatherPic2() + "\",";
                    tableData += "\"weatherPhenomena\":\"" + forecast.getWeatherPhenomena() + "\",";
                    tableData += "\"strWeather1\":\"" + forecast.getStrWeather1() + "\",";
                    tableData += "\"strWeather2\":\"" + forecast.getStrWeather2() + "\",";
                    tableData += "\"week\":\"" + forecast.getWeek() + "\",";
                    tableData += "\"day\":\"" + forecast.getDay() + "\"";
                    tableData += "},";
                }
                tableData = tableData.substring(0, tableData.length() - 1) + "]";
                xValue = xValue.substring(0, xValue.length() - 1) + "]";
                yValue = yValue.substring(0, yValue.length() - 1) + "]";
                yValue1 = yValue1.substring(0, yValue1.length() - 1) + "]";
                yValue = "[{name:'高温',color:'rgba(251,194,118,1)',type:'spline',tooltip:{valueSuffix: '°C'},data:" + yValue + "},"
                        + "{name:'低温',color:'rgba(150,205,247,1)',type:'spline',tooltip:{valueSuffix: '°C'},data:" + yValue1 + "}]";
                temp = tableData + "|" + xValue + "|" + yValue;
            } else {
                temp = "[]";
            }
        } else {
            List<TownshipForecast> fcstList = getNearStaThreeForecast(request, model);
            WebCtrlData wcd = new WebCtrlData();
            temp = "[";
            if (fcstList != null) {
                String xValue = "[";
                String yValue = "[";
                String yValue1 = "[";
                List<Forecast> listResult = new ArrayList<Forecast>();
                int count = fcstList.toArray().length;
                for (int i = 0; i < count; i += 2) {
                    String strforcastSx = fcstList.get(i + 1).getNTimes().toString().trim();
                    DateTime date = dateTime.AddHours(Integer.parseInt(strforcastSx) - 12);

                    SimpleDateFormat dateFm = new SimpleDateFormat("EEEE");
                    String week = dateFm.format(date.toDate());

                    String strDateTime = date.GetDay() + "日";
                    String day = date.GetDay() + "日";


                    String strWeather1 = "";
                    strWeather1 = String.format("%02d", Integer.parseInt(WebCtrlData.WeatherNameToPicPath(fcstList.get(i).getWeather1().toString())));
                    String strWeather2 = "";
                    strWeather2 = String.format("%02d", Integer.parseInt(WebCtrlData.WeatherNameToPicPath(fcstList.get(i + 1).getWeather1().toString())));


                    String strWeatherDisp = "";
                    if (strWeather1.equals("-65535")) {
                        strWeather1 = "00";
                    }
                    if (strWeather2.equals("-65535")) {
                        strWeather2 = "00";
                    }
                    if (strWeather1.equals(strWeather2))
                        strWeatherDisp = wcd.GetWeatherTq(strWeather1).toString();
                    else
                        strWeatherDisp = wcd.GetWeatherTq(strWeather1).toString() + "</br>转"
                                + wcd.GetWeatherTq(strWeather2).toString();


                    strWeather1 = wcd.GetWeatherTq(strWeather1).toString();
                    strWeather2 = wcd.GetWeatherTq(strWeather2).toString();

                    String weatherCode1 = WebCtrlData.WeatherNameToPicPath(strWeather1);
                    String weatherCode2 = WebCtrlData.WeatherNameToPicPath(strWeather2);

                    String strImgPic1 = "<img height='32' width='32' src='../images/tqyb/weatherDay/" + weatherCode1 + ".gif'>";
                    String strImgPic2 = "<img height='32' width='32' src='../images/tqyb/weatherNight/" + weatherCode2
                            + ".gif'>";

                    String strMinTemp = fcstList.get(i).getMinTemp().toString().trim();
                    String strMaxTemp = fcstList.get(i).getMaxTemp().toString().trim();
                    if (strMinTemp.equals("-65535.0") || strMinTemp.equals("65535.0")) {
                        strMinTemp = "";
                    }
                    if (strMaxTemp.equals("-65535.0") || strMaxTemp.equals("65535.0")) {
                        strMaxTemp = "";
                    }
                    String strWindDir1 = "";
                    String strWindDir2 = "";
                    try {
                        strWindDir1 = wcd.GetAllFx(fcstList.get(i).getWindD().toString());
                        strWindDir2 = wcd.GetAllFx(fcstList.get(i + 1).getWindD().toString());
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }

                    if (!strWindDir1.equals(strWindDir2))
                        strWindDir1 = strWindDir1 + "</br>转" + strWindDir2;

                    int minWind = Integer.parseInt(fcstList.get(i + 1).getWindS().toString().substring(0, 1).trim());
                    String minWindS = String.format("%02d", minWind);

                    int maxWind = Integer.parseInt(fcstList.get(i + 1).getWindS().toString().substring(0, 1).trim());
                    String maxWindS = String.format("%02d", maxWind);
                    String strWindDisp = "";
                    if (minWindS.equals(maxWindS))
                        strWindDisp = wcd
                                .GetWeatherFs(String.valueOf(WebCtrlData.FengSuToFengJi(Double.parseDouble(minWindS))))
                                .toString();
                    else
                        strWindDisp = wcd
                                .GetWeatherFs(String.valueOf(WebCtrlData.FengSuToFengJi(Double.parseDouble(minWindS))))
                                .toString() + " </br>转 "
                                + wcd.GetWeatherFs(String.valueOf(WebCtrlData.FengSuToFengJi(Double.parseDouble(maxWindS))))
                                .toString();
                    String strRain = fcstList.get(i).getRain().toString().trim();
                    String strHumid = fcstList.get(i).getHumid().toString().trim();
                    if (strRain.equals("-65535.0") || strRain.equals("65535.0")) {
                        strRain = "";
                    }
                    if (strHumid.equals("-65535.0") || strHumid.equals("65535.0")) {
                        strHumid = "";
                    }
                    Forecast f = new Forecast();
                    f.setDateTime(strDateTime);
                    f.setDay(day);
                    f.setWeek(week);
                    f.setWeatherPhenomena(strWeatherDisp);
                    f.setStrWeather1(strWeather1);
                    f.setStrWeather2(strWeather2);
                    f.setMaxTemp(strMaxTemp);
                    f.setMinTemp(strMinTemp);
                    f.setWindD(strWindDir1);
                    f.setWindV(strWindDisp);
                    f.setWeatherPic1(strImgPic1);
                    f.setWeatherPic2(strImgPic2);
                    f.setRain(strRain);
                    f.setMaxhumid(strHumid);
                    listResult.add(f);

                    xValue += "'" + strDateTime + "',";
                    yValue += strMaxTemp + ",";
                    yValue1 += strMinTemp + ",";
                }

                String tableData = "[";
                for (Forecast forecast : listResult) {
                    tableData += "{";
                    tableData += "\"dateTime\":\"" + forecast.getDateTime() + "\",";
                    tableData += "\"maxTemp\":\"" + forecast.getMaxTemp() + "\",";
                    tableData += "\"minTemp\":\"" + forecast.getMinTemp() + "\",";
                    tableData += "\"windD\":\"" + forecast.getWindD() + "\",";
                    tableData += "\"windV\":\"" + forecast.getWindV() + "\",";
                    tableData += "\"rain\":\"" + forecast.getRain() + "\",";
                    tableData += "\"humid\":\"" + forecast.getMaxhumid() + "\",";
                    tableData += "\"weatherPic1\":\"" + forecast.getWeatherPic1() + "\",";
                    tableData += "\"weatherPic2\":\"" + forecast.getWeatherPic2() + "\",";
                    tableData += "\"weatherPhenomena\":\"" + forecast.getWeatherPhenomena() + "\",";
                    tableData += "\"strWeather1\":\"" + forecast.getStrWeather1() + "\",";
                    tableData += "\"strWeather2\":\"" + forecast.getStrWeather2() + "\",";
                    tableData += "\"week\":\"" + forecast.getWeek() + "\",";
                    tableData += "\"day\":\"" + forecast.getDay() + "\"";
                    tableData += "},";
                    tableData += "{";
                    tableData += "\"dateTime\":\"" + forecast.getDateTime() + "\",";
                    tableData += "\"maxTemp\":\"" + forecast.getMaxTemp() + "\",";
                    tableData += "\"minTemp\":\"" + forecast.getMinTemp() + "\",";
                    tableData += "\"windD\":\"" + forecast.getWindD() + "\",";
                    tableData += "\"windV\":\"" + forecast.getWindV() + "\",";
                    tableData += "\"rain\":\"" + forecast.getRain() + "\",";
                    tableData += "\"humid\":\"" + forecast.getMaxhumid() + "\",";
                    tableData += "\"weatherPic1\":\"" + forecast.getWeatherPic2() + "\",";
                    tableData += "\"weatherPic2\":\"" + forecast.getWeatherPic2() + "\",";
                    tableData += "\"weatherPhenomena\":\"" + forecast.getWeatherPhenomena() + "\",";
                    tableData += "\"strWeather1\":\"" + forecast.getStrWeather1() + "\",";
                    tableData += "\"strWeather2\":\"" + forecast.getStrWeather2() + "\",";
                    tableData += "\"week\":\"" + forecast.getWeek() + "\",";
                    tableData += "\"day\":\"" + forecast.getDay() + "\"";
                    tableData += "},";
                }
                tableData = tableData.substring(0, tableData.length() - 1) + "]";
                xValue = xValue.substring(0, xValue.length() - 1) + "]";
                yValue = yValue.substring(0, yValue.length() - 1) + "]";
                yValue1 = yValue1.substring(0, yValue1.length() - 1) + "]";
                yValue = "[{name:'高温',color:'rgba(251,194,118,1)',type:'spline',tooltip:{valueSuffix: '°C'},data:" + yValue + "},"
                        + "{name:'低温',color:'rgba(150,205,247,1)',type:'spline',tooltip:{valueSuffix: '°C'},data:" + yValue1 + "}]";
                temp = tableData + "|" + xValue + "|" + yValue;
            } else {
                temp = "[]";
            }
        }
        return temp;
    }

    /***
     * 得到最近站点未来七天天气预报
     * @param request
     * @param model
     * @return
     * @throws ParseException
     */
    public List<TownshipForecast> getNearStaThreeForecast(HttpServletRequest request, Model model) throws Exception {
        List<CityFcstInfo> resultList = new ArrayList<CityFcstInfo>();
        String lon = request.getParameter("lon");
        String lat = request.getParameter("lat");
        String time = DateTime.now().toDateString();//; "2020-05-26"// 时间
        String sc = (DateTime.now().GetHour() >= 8 && DateTime.now().GetHour() <= 20) ? "08" : "20";// 时次
        if (DateTime.now().GetHour() >= 8 && DateTime.now().GetHour() < 20)
            sc = "08";
        else if (DateTime.now().GetHour() >= 0 && DateTime.now().GetHour() < 8) {
            time = DateTime.now().AddDays(-1).toDateString(); // 预报时间
            sc = "20";
        } else {
            sc = "20";
        }
        int nTimes = 168;
        TownshipForecastKey selectKey = new TownshipForecastKey();// 查询类
        selectKey.setTimeChar(sc);
        selectKey.setDateChar(DateTime.parseDate(time).toDate());
        selectKey.setNTimes(nTimes);
        List<TownshipForecast> fcstList = forecastInfoService.getNearStaThreeForecast(selectKey, lon, lat);
        return fcstList;
    }

    /***
     * 获取乡镇未来24小时天气预报
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/getWeather")
    @ResponseBody
    public Object getWeather(HttpServletRequest request, Model model) {
        Object list = forecastInfoService.getWeather();
        return list;
    }

    /***
     * 土壤湿度
     * @param request
     * @param model
     * @return
     * @throws ParseException
     */
    @RequestMapping("/soilChart")
    @ResponseBody
    public Object soilChart(HttpServletRequest request, Model model) throws ParseException {
        DateTime currentTime = DateTime.now();
        String startDate = currentTime.AddHours(-23).toDateTimeString("yyyy-MM-dd HH");
        String endDate = currentTime.toDateTimeString("yyyy-MM-dd HH");
        String stationId = request.getParameter("stationId");
        String stationname = request.getParameter("stationname");
        String type = request.getParameter("type");
        if (StringUtil.IsNullOrEmpty(stationId))
            stationId = DbConfig.STATIONID;
        String level = request.getParameter("level");
        if (StringUtil.IsNullOrEmpty(level))
            level = "10";
        List<soil_humidity> resultList = forecastInfoService.soilChart(stationId, startDate, endDate, level);
        // 处理成曲线图
        List<String> hours = new ArrayList<String>();
        List<String> times = new ArrayList<String>();
        Map<String, List<Double>> stationValMap1 = new HashMap<String, List<Double>>();
        for (int i = 0; i < resultList.size(); i++) {
            level = String.valueOf(resultList.get(i).getLevel());
            if (level.equals(String.valueOf(resultList.get(0).getLevel()))) {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd HH");
                String time = simpleDateFormat.format(resultList.get(i).getObservetime());
                hours.add(time);
                SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                times.add(simpleDateFormat1.format(resultList.get(i).getObservetime()));
            }
            List<Double> values1 = new ArrayList<Double>();
            if (!stationValMap1.keySet().contains(level)) {
                if (resultList.get(i).getRelhumidity() != 0 && resultList.get(i).getRelhumidity() != -65535) {
                    values1.add(resultList.get(i).getRelhumidity());
                    stationValMap1.put(level, values1);
                } else {
                    values1.add(0.0);
                }

            } else {
                if (resultList.get(i).getRelhumidity() != 0 && resultList.get(i).getRelhumidity() != -65535) {
                    stationValMap1.get(level).add(resultList.get(i).getRelhumidity());
                }
            }
        }
        ArrayList<Object> result = new ArrayList<Object>();
        result.add(hours);
        result.add(times);
        for (String key : stationValMap1.keySet()) {
            ArrayList<Object> tempArr = new ArrayList<Object>();
            tempArr.add(key);
            tempArr.add(stationValMap1.get(key));
            result.add(tempArr);
        }
        return new ResultObj("查询成功", result, true);
    }

    /***
     * 蒸发量  默认过去10天
     * @param request
     * @param model
     * @return
     * @throws ParseException
     */
    @RequestMapping("/evaporationQuery")
    @ResponseBody
    public Object evaporationQuery(HttpServletRequest request, Model model) throws ParseException {
        System.out.println();

        DateTime currentTime = DateTime.now();
       String startDate = currentTime.AddDays(-10).toDateTimeString("yyyy-MM-dd");

       String endDate = currentTime.toDateTimeString("yyyy-MM-dd");

        String stationId = request.getParameter("stationId");
        if (StringUtil.IsNullOrEmpty(stationId))
//            stationId = "51431";
            stationId = DbConfig.STATIONID;
        List<msgmediumsmallscales> resultList = forecastInfoService.evaporationQuery(startDate, endDate, stationId);
        // 处理成曲线图
        List<String> hours = new ArrayList<String>();
        List<String> times = new ArrayList<String>();
        List<Float> values1 = new ArrayList<Float>();
        Map<String, List<Float>> stationValMap1 = new HashMap<String, List<Float>>();
        if (resultList.size() > 0) {
            String stationname = resultList.get(0).getStationname();
            for (int i = 0; i < resultList.size(); i++) {
                hours.add(resultList.get(i).getDatechar());
                times.add(resultList.get(i).getDatechar());
                values1.add(resultList.get(i).getEvaporation());
            }
            stationValMap1.put(stationname, values1);
            ArrayList<Object> result = new ArrayList<Object>();
            result.add(hours);
            result.add(times);
            for (String key : stationValMap1.keySet()) {
                ArrayList<Object> tempArr = new ArrayList<Object>();
                tempArr.add(key);
                tempArr.add(stationValMap1.get(key));
                result.add(tempArr);
            }
            return new ResultObj("查询成功", result, true);
        } else {
            return new ResultObj("查询失败", "", false);
        }


    }

    /***
     * 气温  默认过去24小时
     * @param request
     * @param model
     * @return
     * @throws ParseException
     */
    @RequestMapping("/tempQuery")
    @ResponseBody
    public Object tempQuery(HttpServletRequest request, Model model) throws ParseException {
        DateTime currentTime = DateTime.now();
//        String startDate = currentTime.AddHours(-23).toDateTimeString("yyyy-MM-dd HH");
        String endDate = currentTime.toDateTimeString("yyyy-MM-dd HH");
        String stationname = request.getParameter("stationId");
        if (StringUtil.IsNullOrEmpty(stationname))
            stationname = DbConfig.STATIONID;
        List<msgmediumsmallscales> resultList = forecastInfoService.tempQuery(endDate, stationname);
        /*************************分布图****************************/
        String picpath = "";
        DateTime cttime = DateTime.now();
        String rainType = "温度";
        String urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\tempPic\\";// 临时文件目录
        FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
        FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
        String s = cttime.AddHours(0).toDateTimeString("yyyy-MM-dd HH:mm:ss");
        String hour = s.substring(11, 13);
        String datechar = cttime.toDateTimeString("yyyy-MM-dd") + " " + hour + ":" + "00" + ":" + "00";
        String fileName = cttime.GetYear() + "_" + cttime.GetMonth() + "_" + cttime.GetDay() + "_" + cttime.GetHour() + "_"
                + rainType + ".png";
        String path = request.getContextPath();
        String servicePath = urlpath + fileName;// 服务器文件
        String basePath = DbConfig.IP + path + "/Temp/tempPic/";
        File serviceFile = new File(servicePath);// 服务器文件
        if (serviceFile.exists()) {// 把文件上传到服务器
            picpath = basePath + fileName;
        } else {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("datechar", datechar);
            map.put("type", rainType);
            map.put("collectionName", "sk_temp_png_file");
            map.put("advCode", DbConfig.advCode);
            byte[] data = ms.selectData(map);
            if (data == null) {
                picpath = "";
            } else {
                FileUtil.bytesToFile(data, servicePath);
                picpath = basePath + fileName;
            }
        }
        // 处理成曲线图
        List<String> hours = new ArrayList<String>();
        List<String> times = new ArrayList<String>();
        List<Object> values1 = new ArrayList<Object>();
        Map<String, List<Object>> stationValMap1 = new HashMap<String, List<Object>>();
        List<msgmediumsmallscales> msgResult = new ArrayList<>();
        for (int i = 0; i < resultList.size(); i++) {
            if (resultList.get(i).getDrybulbtemp() != -65535 && !"中国".equals(resultList.get(i).getCountry())) {
                values1.add(resultList.get(i).getDrybulbtemp());
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd HH");
                String time = simpleDateFormat.format(resultList.get(i).getObservtime());
                hours.add(time);
                SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                times.add(simpleDateFormat1.format(resultList.get(i).getObservtime()));
                msgResult.add(resultList.get(i));
            }
        }
        stationValMap1.put(stationname, values1);
        ArrayList<Object> result = new ArrayList<Object>();
        result.add(hours);
        result.add(times);
        for (String key : stationValMap1.keySet()) {
            ArrayList<Object> tempArr = new ArrayList<Object>();
            tempArr.add(key);
            tempArr.add(stationValMap1.get(key));
            result.add(tempArr);
        }
        result.add(picpath);
        //返回乡镇的温度数据
        result.add(msgResult);
        return new ResultObj("查询成功", result, true);
    }

    /***
     * 干旱监测
     * @param request
     * @param model
     * @return
     * @throws ParseException
     */
    @RequestMapping("/droughtChart")
    @ResponseBody
    public Object droughtChart(HttpServletRequest request, Model model) throws ParseException {
        DateTime currentTime = DateTime.now();
        String startDate = currentTime.AddMonths(-1).toDateString();
        String endDate = currentTime.toDateString();
        String stationname = request.getParameter("stationId");
        if (StringUtil.IsNullOrEmpty(stationname))
            stationname = "57773";
        List<drought> resultList = forecastInfoService.droughtChart(startDate, endDate, stationname);
        // 处理成曲线图
        List<String> hours = new ArrayList<String>();
        List<String> times = new ArrayList<String>();
        List<Float> values1 = new ArrayList<Float>();
        Map<String, List<Float>> stationValMap1 = new HashMap<String, List<Float>>();
        for (int i = 0; i < resultList.size(); i++) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM-dd");
            String time = simpleDateFormat.format(resultList.get(i).getObservationdate());
            hours.add(time);
            SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            times.add(simpleDateFormat1.format(resultList.get(i).getObservationdate()));
            values1.add(resultList.get(i).getDryobservationvalue());
        }
        stationValMap1.put(stationname, values1);
        ArrayList<Object> result = new ArrayList<Object>();
        result.add(hours);
        result.add(times);
        for (String key : stationValMap1.keySet()) {
            ArrayList<Object> tempArr = new ArrayList<Object>();
            tempArr.add(key);
            tempArr.add(stationValMap1.get(key));
            result.add(tempArr);
        }
        return new ResultObj("查询成功", result, true);
    }

    /***
     * 获取菜单信息
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/getMenu")
    @ResponseBody
    public Object getMenu(HttpServletRequest request,Model model){
        String reservoirid = request.getParameter("reservoirid").trim();
        Object list = forecastInfoService.getmenu(reservoirid);
        return list;
    }

    /* 面雨量分析 */
    @RequestMapping("/getSKRainfallAle")           //流域实况面雨量
    @ResponseBody
    public Object getSKRainfallAle(HttpServletRequest request, Model model) throws Exception {
        ArrayList<Object> arrayList = new ArrayList<>();
        List<String> xzList = new ArrayList<String>();
        List<String> lyList = new ArrayList<String>();
        String picpath = "";
        String date = request.getParameter("date");
        String datetime = date+":00:00";// 时间
        String[] ntimes = new String[]{"24","120","240"};
        String areatype = "0"; //0流域  1行政
        List<SurfaceRainResult> resultList = new ArrayList<SurfaceRainResult>();// 最终结果
        for (String ntime : ntimes) {
            SRainfallSearch selectKey = new SRainfallSearch();// 查询类
            selectKey.setStartDate(datetime);//datetime
            selectKey.setNtimes(ntime);
            selectKey.setType("0");//0 实况  1  预报
            selectKey.setAreatype("0");//0 流域  1  行政
            List<area_rain> fcstList = forecastInfoService.getSumAreaRain(selectKey);// 雨量
            List<Rainwatershed> rainwaterList = forecastInfoService.getRainWater(); // 面雨量流域
            for (Rainwatershed rainwater : rainwaterList) {
                for (area_rain msg : fcstList) {
                    if (msg.getAreaname().equals(rainwater.getName())) {
                        SurfaceRainResult result = new SurfaceRainResult();
                        String name = rainwater.getName();
                        Double lon = rainwater.getCenterpointx();
                        Double lat = rainwater.getCenterpointy();
                        result.setName(name);
                        result.setLon(lon);
                        result.setLat(lat);
                        DmMapPoint dmDot = new DmMapPoint(lon, lat);
                        DmMapPoint ltDot = transformService.LonLatConvertToLambert(dmDot.x, dmDot.y);
                        result.setX(ltDot.x);
                        result.setY(ltDot.y);
                        DecimalFormat df = new DecimalFormat("#.0");
                        result.setSurfacerain(Float.parseFloat(df.format(Float.parseFloat(msg.getRain()))));
                        resultList.add(result);
                    }
                }
            }
        }
        return resultList;
    }


    /* 预报面雨量分析 */
    @RequestMapping("/getYBRainfallAle")
    @ResponseBody
    public Object getYBRainfallAle(HttpServletRequest request, Model model) throws Exception {
        ArrayList<Object> arrayList = new ArrayList<>();
        List<String> xzList = new ArrayList<String>();
        List<String> lyList = new ArrayList<String>();
        String picpath = "";
        String datetime = "";
        DateTime time = DateTime.now();
        String newDate = time.toDateTimeString();
        if(time.GetHour()>=8&&time.GetHour()<=20){
            datetime = time.toDateString()+" 08:00:00";// 时间
        }else{
            datetime = time.toDateString()+" 20:00:00";// 时间
        }
        String[] ntimes = new String[]{"24","48","72"};
        String areatype = "1"; //0流域  1行政

        for (String ntime : ntimes) {
            SRainfallSearch selectKey = new SRainfallSearch();// 查询类
            if(time.GetHour()>=8&&time.GetHour()<=20){
                datetime = time.toDateString()+" 08:00:00";// 时间
            }else{
                datetime = time.toDateString()+" 20:00:00";// 时间
            }
            selectKey.setStartDate(datetime);
            selectKey.setNtimes(ntime);
            selectKey.setType("1");//0 实况  1  预报
            selectKey.setAreatype("0");//0 流域  1  行政
            List<area_rain> fcstList = forecastInfoService.getSumAreaRain(selectKey);
            arrayList.add(fcstList);
        }
        return arrayList;
    }

    @RequestMapping("/getQPF")
    @ResponseBody
    public Object getQPF(String data, String type, String area) {
        String newDate = forecastInfoService.getQPFNewDate();
        List<QPF> listQPF = forecastInfoService.getQPF(newDate, area);
        if (listQPF.size() != 0) {
            List<Map> result = new ArrayList<>();
            Map<String, Object> map = new HashMap<>();
            for (int i = 0; i < listQPF.size(); i++) {
                QPF rain = listQPF.get(i);
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String format = df.format(rain.getDatechar().getTime() + (rain.getNtimes()-10) * 60 * 1000);

                if (rain.getType().equals( "0")) {
                    map = new HashMap<>();
                    map.put("时间", format);
                    map.put("雨量值", String.format("%.2f", Double.parseDouble(rain.getValue())));
                } else {
                    map.put("累计雨量值", String.format("%.2f", Double.parseDouble(rain.getValue())));
                    result.add(map);
                }
            }
            return new ResultObj("获取成功", result, true);
        }
        return new ResultObj("获取成功", null, false);
    }
    @RequestMapping("getQPFJPG")
    @ResponseBody
    public Object getQPFJPG(HttpServletRequest request) {
        List<AreaPoji> rains = new ArrayList<>();
        String newDate = forecastInfoService.getQPFNewDate();
        String drainagearea = request.getParameter("area");//流域
        if (StringUtil.IsNullOrEmpty(drainagearea))
            drainagearea = DbConfig.DRAINAGEAREA;
        String rstpath = "";

        String urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\QpfMap\\";
        FileUtil.mkDirs(urlpath);// 创建文件夹
        // 当图片达到1000张时清除
        FileUtil.ClearTempFiles(urlpath, 1000);
        for (int i = 10; i <= 60; i=i+10) {
            try {
                AreaPoji r = new AreaPoji();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//注意月份是MM
                Date date = simpleDateFormat.parse(newDate);
                simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmm");//注意月份是MM
                String newDate1 = simpleDateFormat.format(date);
                String ntimes = "0" + Integer.toString(i);
                String fileName = newDate1 + "_" + ntimes + ".png";
                String servicePath = urlpath + fileName;
                String path = request.getContextPath();
                String basePath = DbConfig.IP + path + "/Temp/QpfMap/";
                File serviceFile = new File(servicePath);
                if (serviceFile.exists()) {
                    rstpath = basePath + fileName;
                } else {
                    // 从mongdb获取图片
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("datechar", newDate1);
                    map.put("type", "QPF");
                    map.put("ntimes", ntimes);
                    map.put("drainagearea", drainagearea);
                    map.put("collectionName", "qpf_png_sl_file");
                    map.put("advCode", DbConfig.advCode);
                    byte[] data = ms.selectData(map);
                    if (data == null) {
                        rstpath = "";
                    } else {
                        FileUtil.bytesToFile(data, servicePath);
                        rstpath = basePath + fileName;
                    }
                }
                r.setPath(rstpath);
                SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月dd日HH时mm分");
                String strtime = df.format(date.getTime() + (i - 10) * 60 * 1000);
                String endime = df.format(date.getTime() + (i) * 60 * 1000);
                r.setTime(strtime + "-" + endime);
                rains.add(r);
            }
            catch (Exception ex)
            {
                continue;
            }
        }
        return new ResultObj("获取成功", rains, true);
    }

    /* 中长期产品类型 */
    @RequestMapping("/getProductType")
    @ResponseBody
    public Object getProductType(HttpServletRequest request, Model model) throws Exception {
        List<String> proTypeList = new ArrayList<String>();
        List<job_model> jobList = forecastInfoService.getProductType();
        return new ResultObj("获取成功", jobList, true);
    }

    /**
     * 得到常规服务文档
     * @param request
     * @param model
     * @returnshowCommonDoc
     * @throws ParseException
     */
    @RequestMapping("/getCommonWord")
    @ResponseBody
    public Object getCommonWord(HttpServletRequest request, Model model) throws ParseException {
        String bigtype = request.getParameter("bigtype");
        String smalltype = request.getParameter("smalltype");
        List<summary_product> resultList = forecastInfoService.getCommonWord(bigtype, smalltype);
        return resultList;
    }

    /**
     * 显示常规服务文档
     * @param request
     * @param model
     * @return
     * @throws ParseException
     */
    @RequestMapping("/showCommonDoc")
    @ResponseBody
    public Object showCommonDoc(HttpServletRequest request, Model model) throws ParseException {
        String servicePath = "";
        String bigtype = request.getParameter("bigtype");
        String id = request.getParameter("id"); // 获取编号
        String fileName = request.getParameter("filename");
        String urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\CommonWord\\"; // 临时文件目录
        FileUtil.mkDirs(urlpath); // 创建文件夹，生成多级目录
        FileUtil.ClearTempFiles(urlpath, 1000); // 清除缓存
        String doctype = fileName.split("\\.")[fileName.split("\\.").length - 1]; // 文件类型
        if (doctype.contains("doc")) {
            String localPath = urlpath + fileName;
            String pdfPath = urlpath + fileName.replace(doctype, "pdf");
            File pdfFile = new File(pdfPath);
            if (pdfFile.exists()) {
                servicePath = "Temp\\CommonWord\\" + fileName.replace(doctype, "pdf");
            } else {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("id", id);
                map.put("table_name", "summary_product");
                map.put("collectionName", "pdf_file");
                if (!bigtype.equals("省级")&&!bigtype.contains("为农气象服务"))
                    map.put("advCode", DbConfig.advCode);
                byte[] data = ms.selectData(map);
                if (data.length > 0) {
                    FileUtil.bytesToFile(data, pdfPath);
                    // 下载doc文件
                    if (data == null) {
                        return "";
                    }
                    File localFile = new File(pdfPath); // 本地文件
                    if (localFile.exists()) {
                        try {
                            servicePath = "Temp\\CommonWord\\" + fileName.replace(doctype, "pdf");
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        servicePath = servicePath.replace("\\", "/");
        return servicePath;
    }

    /* 产品类型 */
    @RequestMapping("/getPublishType")
    @ResponseBody
    public  List<String> getPublishType(HttpServletRequest request, Model model) throws Exception {
        List<String> proTypeList=new ArrayList<String>();
        List<sys_config> cfg = configService.getSysConfig("发布产品");
        if(cfg.size()>0)
        {
            String types=cfg.get(0).getParamvalue();
            String[] tpList=types.split(";");
            for(String val :tpList)
                proTypeList.add(val);
        }
        return proTypeList;
    }

    /* 产品发布信息 */
    @RequestMapping("/getPublishRecord")
    @ResponseBody
    public Object getPublishRecord(HttpServletRequest request, Model model) throws Exception {
        String startDate = request.getParameter("startDate");
        String endDate = request.getParameter("endDate");
        String productType=request.getParameter("type");
        String areaName=request.getParameter("areaName");
        Object res = forecastInfoService.getPublishRecord(startDate,endDate,productType,areaName);
        return res;
    }

    /***
     * 获取水位监测最新数据的时间
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/getneartime")
    @ResponseBody
    public Object getneartime(HttpServletRequest request,Model model){
        Object list = forecastInfoService.getneartime();
        return list;
    }
}
